source: bookmarks/trunk/BookmarkApp.pm @ 32

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