source: bookmarks/trunk/BookmarkApp.pm @ 40

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