source: bookmarks/trunk/BookmarkApp.pm @ 37

Last change on this file since 37 was 37, checked in by peter, 11 years ago
  • moved the creation of the $bookmarks and $base_uri objects into the BookmarkApp::setup() method; they are now parameters of the app
  • added a _bookmarks accessor as a shortcut to get the bookmarks object
File size: 10.7 KB
RevLine 
[5]1package BookmarkApp;
2use strict;
3use warnings;
4use base qw{CGI::Application};
5
[6]6use CGI::Application::Plugin::TT;
7
[5]8use Encode;
[19]9use HTTP::Date qw{time2isoz};
[5]10use JSON;
11use Bookmarks;
12
[7]13use URI;
14
[15]15my $dbname = 'fk.db';
[5]16
17sub setup {
18    my $self = shift;
19    $self->mode_param(path_info => 1);
20    $self->run_modes([qw{
21        list
[9]22        feed
[5]23        view
[30]24        view_field
[5]25        edit
26    }]);
[37]27    my $base_uri = URI->new;
28    $base_uri->scheme('http');
29    $base_uri->host($ENV{HTTP_X_FORWARDED_HOST} || $ENV{SERVER_NAME});
30    $base_uri->port($ENV{SERVER_PORT});
31    $base_uri->path($ENV{SCRIPT_NAME} . '/');
32
33    my $bookmarks = Bookmarks->new({
34        dbname   => $dbname,
35        base_uri => $base_uri,
36    });
37
38    $self->param(
39        base_uri  => $base_uri,
40        bookmarks => $bookmarks,
41    );
[5]42}
43
[37]44sub _bookmarks { $_[0]->param('bookmarks') }
45
[5]46sub list {
47    my $self = shift;
48    my $q = $self->query;
49
50    # check for a uri param, and if there is one present,
51    # see if a bookmark for that URI already exists
52    if (defined(my $uri = $q->param('uri'))) {
[37]53        my $bookmark = $self->_bookmarks->get_bookmark({ uri => $uri });
[5]54        if ($bookmark) {
55            # redirect to the view of the existing bookmark
56            $self->header_type('redirect');
57            $self->header_props(
58                -uri => $q->url . '/' . $bookmark->{id},
59            );
60            return;
61        } else {
62            # bookmark was not found; show the form to create a new bookmark
63            $bookmark->{uri} = $uri;
64            $bookmark->{title} = $q->param('title');
65            $self->header_props(
66                -type    => 'text/html',
67                -charset => 'UTF-8',
68                -status  => 404,
69            );
[6]70            return $self->tt_process(
[5]71                'bookmark.tt',
72                $bookmark,
73            );
74        }
75    }
76
77    # list all the bookmarks
78    my $format = $q->param('format') || 'html';
[35]79
80    my @tags = grep { $_ ne '' } $q->param('tag');
[13]81    my $limit = $q->param('limit');
82    my $offset = $q->param('offset');
[37]83    my @resources = $self->_bookmarks->get_bookmarks({
[20]84        tag    => \@tags,
[13]85        limit  => $limit,
86        offset => $offset,
87    });
[37]88    my @all_tags = $self->_bookmarks->get_tags({ selected => $tags[0] });
89    my @cotags = $self->_bookmarks->get_cotags({ tag => \@tags });
[31]90   
91    my $title = 'Bookmarks' . (@tags ? " tagged as " . join(' & ', @tags) : '');
[5]92
93    if ($format eq 'json') {
94        $self->header_props(
95            -type    => 'application/json',
96            -charset => 'UTF-8',
97        );
98        return decode_utf8(
[25]99            JSON->new->utf8->convert_blessed->encode({
[7]100                bookmarks => \@resources,
[5]101            })
102        );
[19]103    } elsif ($format eq 'xbel') {
104        require XML::XBEL;
105        #TODO: conditional support; if XML::XBEL is not present, return a 5xx response
106
107        my $xbel = XML::XBEL->new;
108
109        $xbel->new_document({
[31]110            title => $title,
[19]111        });
112
113        for my $bookmark (@resources) {
[36]114            my $cdatetime = time2isoz $bookmark->ctime;
115            my $mdatetime = time2isoz $bookmark->mtime;
[19]116            # make the timestamps W3C-correct
117            s/ /T/ foreach ($cdatetime, $mdatetime);
118
119            $xbel->add_bookmark({
[36]120                href     => $bookmark->uri,
121                title    => $bookmark->title,
122                desc     => 'Tags: ' . join(', ', @{ $bookmark->tags }),
[19]123                added    => $cdatetime,
124                #XXX: are we sure that modified is the mtime of the bookmark or the resource?
125                modified => $mdatetime,
126            });
127        }
128
129        $self->header_props(
130            -type    => 'application/xml',
131            -charset => 'UTF-8',
132        );
133
134        return $xbel->toString;
[36]135    } elsif ($format eq 'text') {
136        $self->header_props(
137            -type    => 'text/uri-list',
138            -charset => 'UTF-8',
139        );
140        return join '', 
141            map {
142                sprintf "# %s\n# Tags: %s\n%s\n",
143                $_->title,
144                join(', ', @{ $_->tags }), 
145                $_->uri
146            } @resources;
[5]147    } else {
148        $self->header_props(
149            -type    => 'text/html',
150            -charset => 'UTF-8',
151        );
152
153        # set the base URL, adding a trailing slash if needed
154        my $base_url = $q->url;
155        $base_url .= '/' if $base_url =~ m{/bookmarks$};
156
[22]157        my @links = (
158            {
159                text => 'Link',
160                type => 'text/html',
161                rel  => 'self',
162                query => {
163                    tag => \@tags,
164                },
165            },
166            {
167                text => 'JSON',
168                type => 'application/json',
169                rel  => 'alternate',
170                query => {
171                    tag => \@tags,
172                    format => 'json',
173                },
174            },
175            {
176                text => 'XBEL',
177                type => 'application/xml',
178                rel  => 'alternate',
179                query => {
180                    tag => \@tags,
181                    format => 'xbel',
182                },
183            },
184            {
185                text => 'Atom',
186                type => 'application/atom+xml',
187                rel  => 'alternate',
188                path => 'feed',
189                query => {
190                    tag => \@tags,
191                },
192            },
193        );
194        for my $link (@links) {
[37]195            $link->{href} = URI->new_abs($link->{path} || '', $self->param('base_uri'));
[22]196            $link->{href}->query_form($link->{query});
197        }
[31]198
[6]199        return $self->tt_process(
[5]200            'list.tt',
201            {
202                base_url     => $base_url,
[31]203                title        => $title,
[35]204                selected_tag => $tags[0],
[20]205                search_tags  => \@tags,
[22]206                links        => \@links,
[20]207                all_tags     => \@all_tags,
[5]208                cotags       => \@cotags,
209                resources    => \@resources,
210            },
211        );
212    }
213}
214
[9]215sub feed {
216    my $self = shift;
217    my $q = $self->query;
218
[35]219    my @tags = grep { $_ ne '' } $q->param('tag');
[31]220    my $title = 'Bookmarks' . (@tags ? " tagged as " . join(' & ', @tags) : '');
221
[33]222    require XML::Atom;
223    $XML::Atom::DefaultVersion = "1.0";
224
[9]225    require XML::Atom::Feed;
226    require XML::Atom::Entry;
227    require XML::Atom::Link;
228
229    my $feed = XML::Atom::Feed->new;
[31]230    $feed->title($title);
[32]231
[37]232    my $feed_uri = URI->new_abs('feed', $self->param('base_uri'));
[32]233    $feed_uri->query_form(tag => \@tags);
234    $feed->id($feed_uri->canonical);
235
236    my $self_link = XML::Atom::Link->new;
237    $self_link->type('application/atom+xml');
238    $self_link->rel('self');
239    $self_link->href($feed_uri->canonical);
240    $feed->add_link($self_link);
241
[31]242    my $html_link = XML::Atom::Link->new;
243    $html_link->type('text/html');
244    $html_link->rel('alternate');
[37]245    my $html_uri = $self->param('base_uri')->clone;
[32]246    $html_uri->query_form(tag => \@tags);
247    $html_link->href($html_uri->canonical);
[31]248    $feed->add_link($html_link);
[9]249
250    # construct a feed from the most recent 12 bookmarks
[37]251    for my $bookmark ($self->_bookmarks->get_bookmarks({ tag => \@tags, limit => 12 })) {
[9]252        my $entry = XML::Atom::Entry->new;
[31]253        $entry->id($bookmark->bookmark_uri->canonical);
254        $entry->title($bookmark->title);
[9]255        my $link = XML::Atom::Link->new;
[31]256        $link->href($bookmark->uri);
[9]257        $entry->add_link($link);
[31]258        $entry->summary('Tags: ' . join(', ', @{ $bookmark->tags }));
[33]259        my $mdatetime = time2isoz $bookmark->mtime;
260        # make the timestamp W3C-correct
261        $mdatetime =~ s/ /T/;
262        $entry->updated($mdatetime);
[9]263        $feed->add_entry($entry);
264    }
265
266    $self->header_props(
267        -type => 'application/atom+xml',
268        -charset => 'UTF-8',
269    );
270    return $feed->as_xml;
271}
272
[5]273sub view {
274    my $self = shift;
275    my $id = $self->param('id');
[7]276    my $format = $self->query->param('format') || 'html';
[5]277
[37]278    my $bookmark = $self->_bookmarks->get_bookmark({ id => $id });
[5]279    if ($bookmark) {
[30]280        if ($format eq 'json') {
[5]281            $self->header_props(
[30]282                -type    => 'application/json',
[5]283                -charset => 'UTF-8',
284            );
[30]285            return decode_utf8(JSON->new->utf8->convert_blessed->encode($bookmark));
[5]286        } else {
[30]287            # display the bookmark form for this bookmark
288            $bookmark->{exists} = 1;
289            $bookmark->{created} = "Created " . localtime($bookmark->ctime);
290            $bookmark->{created} .= '; Updated ' . localtime($bookmark->mtime) unless $bookmark->ctime == $bookmark->mtime;
291            $self->header_props(
292                -type    => 'text/html',
293                -charset => 'UTF-8',
294            );
295            return $self->tt_process(
296                'bookmark.tt',
297                $bookmark,
298            );
299        }
300    } else {
301        $self->header_props(
302            -type    => 'text/html',
303            -charset => 'UTF-8',
304            -status  => 404,
305        );
306        return "Bookmark $id Not Found";
307    }
308}
309
310sub view_field {
311    my $self = shift;
312    my $id = $self->param('id');
313    my $field = $self->param('field');
314
[37]315    my $bookmark = $self->_bookmarks->get_bookmark({ id => $id });
[30]316    if ($bookmark) {
317        # respond with just the requested field as plain text
318        my $value = eval { $bookmark->$field };
319        if ($@) {
320            if ($@ =~ /Can't locate object method/) {
[7]321                $self->header_props(
[30]322                    -type    => 'text/plain',
[7]323                    -charset => 'UTF-8',
[30]324                    -status  => 404,
[7]325                );
[30]326                return qq{"$field" is not a valid bookmark data field};
[7]327            } else {
[30]328                die $@;
[7]329            }
[5]330        }
[30]331        $self->header_props(
332            -type    => 'text/plain',
333            -charset => 'UTF-8',
334        );
335        return ref $value eq 'ARRAY' ? join(',', @{ $value }) : $value;
[5]336    } else {
337        $self->header_props(
338            -type    => 'text/html',
339            -charset => 'UTF-8',
340            -status  => 404,
341        );
342        return "Bookmark $id Not Found";
343    }
344}
345
346#TODO: split this into edit and create methods
347sub edit {
348    my $self = shift;
349    my $q = $self->query;
350    #TODO: get the bookmark based on the id and edit it directly?
351    #TODO: deal with changing URIs
352    my $uri = $q->param('uri');
353    my $title = $q->param('title');
354    my @tags = split ' ', $q->param('tags');
[37]355    $self->_bookmarks->add({
[5]356        uri   => $uri,
357        title => $title,
358        tags  => \@tags,
359    });
360
361=begin
362
363    my $location = URI->new($q->url);
364    $location->query_form(uri => $uri) if defined $q->url_param('uri');
365    $location->fragment('updated');
366
367=cut
368
369    # return to the form
370    $self->header_type('redirect');
371    $self->header_props(
372        -uri => $ENV{REQUEST_URI},
373        -status => 303,
374    );
375}
376
3771;
Note: See TracBrowser for help on using the repository browser.