source: bookmarks/trunk/BookmarkApp.pm @ 43

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