source: bookmarks/trunk/BookmarkApp.pm @ 38

Last change on this file since 38 was 38, checked in by peter, 11 years ago
  • put the list of links to alternate formats for the list into a _get_list_links method
  • the HTML and Atom Feed views use the same list of alternate links
  • added the text/uri-list format to the list of alternate list links
File size: 10.6 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;
12use URI;
13
14my $dbname = 'fk.db';
15
16sub setup {
17    my $self = shift;
18    $self->mode_param(path_info => 1);
19    $self->run_modes([qw{
20        list
21        feed
22        view
23        view_field
24        edit
25    }]);
26    my $base_uri = URI->new;
27    $base_uri->scheme('http');
28    $base_uri->host($ENV{HTTP_X_FORWARDED_HOST} || $ENV{SERVER_NAME});
29    $base_uri->port($ENV{SERVER_PORT});
30    $base_uri->path($ENV{SCRIPT_NAME} . '/');
31
32    my $bookmarks = Bookmarks->new({
33        dbname   => $dbname,
34        base_uri => $base_uri,
35    });
36
37    $self->param(
38        base_uri  => $base_uri,
39        bookmarks => $bookmarks,
40    );
41}
42
43sub _bookmarks { $_[0]->param('bookmarks') }
44
45sub _get_list_links {
46    my $self = shift;
47    my ($self_type, $tags) = @_;
48    my @links = (
49        {
50            text => 'HTML',
51            type => 'text/html',
52            query => {
53                tag => $tags,
54            },
55        },
56        {
57            text => 'JSON',
58            type => 'application/json',
59            query => {
60                tag => $tags,
61                format => 'json',
62            },
63        },
64        {
65            text => 'XBEL',
66            type => 'application/xml',
67            query => {
68                tag => $tags,
69                format => 'xbel',
70            },
71        },
72        {
73            text => 'Atom',
74            type => 'application/atom+xml',
75            path => 'feed',
76            query => {
77                tag => $tags,
78            },
79        },
80        {
81            text => 'URI List',
82            type => 'text/uri-list',
83            query => {
84                tag => $tags,
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
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'))) {
105        my $bookmark = $self->_bookmarks->get_bookmark({ uri => $uri });
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            );
122            return $self->tt_process(
123                'bookmark.tt',
124                $bookmark,
125            );
126        }
127    }
128
129    # list all the bookmarks
130    my $format = $q->param('format') || 'html';
131
132    my @tags = grep { $_ ne '' } $q->param('tag');
133    my $limit = $q->param('limit');
134    my $offset = $q->param('offset');
135    my @resources = $self->_bookmarks->get_bookmarks({
136        tag    => \@tags,
137        limit  => $limit,
138        offset => $offset,
139    });
140    my @all_tags = $self->_bookmarks->get_tags({ selected => $tags[0] });
141    my @cotags = $self->_bookmarks->get_cotags({ tag => \@tags });
142   
143    my $title = 'Bookmarks' . (@tags ? " tagged as " . join(' & ', @tags) : '');
144
145    if ($format eq 'json') {
146        $self->header_props(
147            -type    => 'application/json',
148            -charset => 'UTF-8',
149        );
150        return decode_utf8(
151            JSON->new->utf8->convert_blessed->encode({
152                bookmarks => \@resources,
153            })
154        );
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({
162            title => $title,
163        });
164
165        for my $bookmark (@resources) {
166            my $cdatetime = time2isoz $bookmark->ctime;
167            my $mdatetime = time2isoz $bookmark->mtime;
168            # make the timestamps W3C-correct
169            s/ /T/ foreach ($cdatetime, $mdatetime);
170
171            $xbel->add_bookmark({
172                href     => $bookmark->uri,
173                title    => $bookmark->title,
174                desc     => 'Tags: ' . join(', ', @{ $bookmark->tags }),
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;
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;
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
209        return $self->tt_process(
210            'list.tt',
211            {
212                base_url     => $base_url,
213                title        => $title,
214                selected_tag => $tags[0],
215                search_tags  => \@tags,
216                links        => [ $self->_get_list_links('text/html', \@tags) ],
217                all_tags     => \@all_tags,
218                cotags       => \@cotags,
219                resources    => \@resources,
220            },
221        );
222    }
223}
224
225sub feed {
226    my $self = shift;
227    my $q = $self->query;
228
229    my @tags = grep { $_ ne '' } $q->param('tag');
230    my $title = 'Bookmarks' . (@tags ? " tagged as " . join(' & ', @tags) : '');
231
232    require XML::Atom;
233    $XML::Atom::DefaultVersion = "1.0";
234
235    require XML::Atom::Feed;
236    require XML::Atom::Entry;
237    require XML::Atom::Link;
238
239    my $feed = XML::Atom::Feed->new;
240    $feed->title($title);
241
242    my $feed_uri = URI->new_abs('feed', $self->param('base_uri'));
243    $feed_uri->query_form(tag => \@tags);
244    $feed->id($feed_uri->canonical);
245
246    for my $link ($self->_get_list_links('application/atom+xml', \@tags)) {
247        my $atom_link = XML::Atom::Link->new;
248        $atom_link->type($link->{type});
249        $atom_link->rel($link->{rel});
250        $atom_link->href($link->{href}->canonical);
251        $feed->add_link($atom_link);
252    }
253
254    # construct a feed from the most recent 12 bookmarks
255    for my $bookmark ($self->_bookmarks->get_bookmarks({ tag => \@tags, limit => 12 })) {
256        my $entry = XML::Atom::Entry->new;
257        $entry->id($bookmark->bookmark_uri->canonical);
258        $entry->title($bookmark->title);
259        my $link = XML::Atom::Link->new;
260        $link->href($bookmark->uri);
261        $entry->add_link($link);
262        $entry->summary('Tags: ' . join(', ', @{ $bookmark->tags }));
263        my $mdatetime = time2isoz $bookmark->mtime;
264        # make the timestamp W3C-correct
265        $mdatetime =~ s/ /T/;
266        $entry->updated($mdatetime);
267        $feed->add_entry($entry);
268    }
269
270    $self->header_props(
271        -type => 'application/atom+xml',
272        -charset => 'UTF-8',
273    );
274    return $feed->as_xml;
275}
276
277sub view {
278    my $self = shift;
279    my $id = $self->param('id');
280    my $format = $self->query->param('format') || 'html';
281
282    my $bookmark = $self->_bookmarks->get_bookmark({ id => $id });
283    if ($bookmark) {
284        if ($format eq 'json') {
285            $self->header_props(
286                -type    => 'application/json',
287                -charset => 'UTF-8',
288            );
289            return decode_utf8(JSON->new->utf8->convert_blessed->encode($bookmark));
290        } else {
291            # display the bookmark form for this bookmark
292            $bookmark->{exists} = 1;
293            $bookmark->{created} = "Created " . localtime($bookmark->ctime);
294            $bookmark->{created} .= '; Updated ' . localtime($bookmark->mtime) unless $bookmark->ctime == $bookmark->mtime;
295            $self->header_props(
296                -type    => 'text/html',
297                -charset => 'UTF-8',
298            );
299            return $self->tt_process(
300                'bookmark.tt',
301                $bookmark,
302            );
303        }
304    } else {
305        $self->header_props(
306            -type    => 'text/html',
307            -charset => 'UTF-8',
308            -status  => 404,
309        );
310        return "Bookmark $id Not Found";
311    }
312}
313
314sub view_field {
315    my $self = shift;
316    my $id = $self->param('id');
317    my $field = $self->param('field');
318
319    my $bookmark = $self->_bookmarks->get_bookmark({ id => $id });
320    if ($bookmark) {
321        # respond with just the requested field as plain text
322        my $value = eval { $bookmark->$field };
323        if ($@) {
324            if ($@ =~ /Can't locate object method/) {
325                $self->header_props(
326                    -type    => 'text/plain',
327                    -charset => 'UTF-8',
328                    -status  => 404,
329                );
330                return qq{"$field" is not a valid bookmark data field};
331            } else {
332                die $@;
333            }
334        }
335        $self->header_props(
336            -type    => 'text/plain',
337            -charset => 'UTF-8',
338        );
339        return ref $value eq 'ARRAY' ? join(',', @{ $value }) : $value;
340    } else {
341        $self->header_props(
342            -type    => 'text/html',
343            -charset => 'UTF-8',
344            -status  => 404,
345        );
346        return "Bookmark $id Not Found";
347    }
348}
349
350#TODO: split this into edit and create methods
351sub edit {
352    my $self = shift;
353    my $q = $self->query;
354    #TODO: get the bookmark based on the id and edit it directly?
355    #TODO: deal with changing URIs
356    my $uri = $q->param('uri');
357    my $title = $q->param('title');
358    my @tags = split ' ', $q->param('tags');
359    $self->_bookmarks->add({
360        uri   => $uri,
361        title => $title,
362        tags  => \@tags,
363    });
364
365=begin
366
367    my $location = URI->new($q->url);
368    $location->query_form(uri => $uri) if defined $q->url_param('uri');
369    $location->fragment('updated');
370
371=cut
372
373    # return to the form
374    $self->header_type('redirect');
375    $self->header_props(
376        -uri => $ENV{REQUEST_URI},
377        -status => 303,
378    );
379}
380
3811;
Note: See TracBrowser for help on using the repository browser.