source: bookmarks/trunk/BookmarkApp.pm @ 37

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