source: bookmarks/trunk/BookmarkApp.pm @ 36

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