source: bookmarks/trunk/BookmarkApp.pm @ 41

Last change on this file since 41 was 41, checked in by peter, 11 years ago
  • move the reverse proxy check and change to SERVER_NAME from the BookmarkApp to the index.cgi script
  • the dbname is passed in as a parameter to BookmarkApp
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
14sub setup {
15    my $self = shift;
16    $self->mode_param(path_info => 1);
17    $self->run_modes([qw{
18        list
19        feed
20        view
21        view_field
22        edit
23    }]);
24
25    my $base_uri = URI->new;
26    $base_uri->scheme('http');
27    $base_uri->host($ENV{SERVER_NAME});
28    $base_uri->port($ENV{SERVER_PORT});
29    $base_uri->path($ENV{SCRIPT_NAME} . '/');
30
31    my $bookmarks = Bookmarks->new({
32        dbname   => $self->param('dbname'),
33        base_uri => $base_uri,
34    });
35
36    $self->param(
37        base_uri  => $base_uri,
38        bookmarks => $bookmarks,
39    );
40}
41
42sub _bookmarks { $_[0]->param('bookmarks') }
43
44sub _get_list_links {
45    my $self = shift;
46    my ($self_type, $tags) = @_;
47    my @links = (
48        {
49            text => 'HTML',
50            type => 'text/html',
51            query => {
52                tag => $tags,
53            },
54        },
55        {
56            text => 'JSON',
57            type => 'application/json',
58            query => {
59                tag => $tags,
60                format => 'json',
61            },
62        },
63        {
64            text => 'XBEL',
65            type => 'application/xml',
66            query => {
67                tag => $tags,
68                format => 'xbel',
69            },
70        },
71        {
72            text => 'Atom',
73            type => 'application/atom+xml',
74            path => 'feed',
75            query => {
76                tag => $tags,
77            },
78        },
79        {
80            text => 'URI List',
81            type => 'text/uri-list',
82            query => {
83                tag => $tags,
84                format => 'text',
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    require XML::Atom::Category;
239
240    my $feed = XML::Atom::Feed->new;
241    $feed->title($title);
242
243    my $feed_uri = URI->new_abs('feed', $self->param('base_uri'));
244    $feed_uri->query_form(tag => \@tags);
245    $feed->id($feed_uri->canonical);
246
247    for my $link ($self->_get_list_links('application/atom+xml', \@tags)) {
248        my $atom_link = XML::Atom::Link->new;
249        $atom_link->type($link->{type});
250        $atom_link->rel($link->{rel});
251        $atom_link->href($link->{href}->canonical);
252        $feed->add_link($atom_link);
253    }
254
255    # construct a feed from the most recent 12 bookmarks
256    for my $bookmark ($self->_bookmarks->get_bookmarks({ tag => \@tags, limit => 12 })) {
257        my $entry = XML::Atom::Entry->new;
258        $entry->id($bookmark->bookmark_uri->canonical);
259        $entry->title($bookmark->title);
260       
261        my $link = XML::Atom::Link->new;
262        $link->href($bookmark->uri);
263        $entry->add_link($link);
264       
265        $entry->summary('Tags: ' . join(', ', @{ $bookmark->tags }));
266
267        my $cdatetime = time2isoz $bookmark->ctime;
268        my $mdatetime = time2isoz $bookmark->mtime;
269        # make the timestamp W3C-correct
270        s/ /T/ foreach ($cdatetime, $mdatetime);
271        $entry->published($cdatetime);
272        $entry->updated($mdatetime);
273       
274        for my $tag (@{ $bookmark->tags }) {
275            my $category = XML::Atom::Category->new;
276            $category->term($tag);
277            $entry->add_category($category);
278        }
279
280        $feed->add_entry($entry);
281    }
282
283    $self->header_props(
284        -type => 'application/atom+xml',
285        -charset => 'UTF-8',
286    );
287    return $feed->as_xml;
288}
289
290sub view {
291    my $self = shift;
292    my $id = $self->param('id');
293    my $format = $self->query->param('format') || 'html';
294
295    my $bookmark = $self->_bookmarks->get_bookmark({ id => $id });
296    if ($bookmark) {
297        if ($format eq 'json') {
298            $self->header_props(
299                -type    => 'application/json',
300                -charset => 'UTF-8',
301            );
302            return decode_utf8(JSON->new->utf8->convert_blessed->encode($bookmark));
303        } else {
304            # display the bookmark form for this bookmark
305            $bookmark->{exists} = 1;
306            $bookmark->{created} = "Created " . localtime($bookmark->ctime);
307            $bookmark->{created} .= '; Updated ' . localtime($bookmark->mtime) unless $bookmark->ctime == $bookmark->mtime;
308            $self->header_props(
309                -type    => 'text/html',
310                -charset => 'UTF-8',
311            );
312            return $self->tt_process(
313                'bookmark.tt',
314                $bookmark,
315            );
316        }
317    } else {
318        $self->header_props(
319            -type    => 'text/html',
320            -charset => 'UTF-8',
321            -status  => 404,
322        );
323        return "Bookmark $id Not Found";
324    }
325}
326
327sub view_field {
328    my $self = shift;
329    my $id = $self->param('id');
330    my $field = $self->param('field');
331
332    my $bookmark = $self->_bookmarks->get_bookmark({ id => $id });
333    if ($bookmark) {
334        # respond with just the requested field as plain text
335        my $value = eval { $bookmark->$field };
336        if ($@) {
337            if ($@ =~ /Can't locate object method/) {
338                $self->header_props(
339                    -type    => 'text/plain',
340                    -charset => 'UTF-8',
341                    -status  => 404,
342                );
343                return qq{"$field" is not a valid bookmark data field};
344            } else {
345                die $@;
346            }
347        }
348        $self->header_props(
349            -type    => 'text/plain',
350            -charset => 'UTF-8',
351        );
352        return ref $value eq 'ARRAY' ? join(',', @{ $value }) : $value;
353    } else {
354        $self->header_props(
355            -type    => 'text/html',
356            -charset => 'UTF-8',
357            -status  => 404,
358        );
359        return "Bookmark $id Not Found";
360    }
361}
362
363#TODO: split this into edit and create methods
364sub edit {
365    my $self = shift;
366    my $q = $self->query;
367    #TODO: get the bookmark based on the id and edit it directly?
368    #TODO: deal with changing URIs
369    my $uri = $q->param('uri');
370    my $title = $q->param('title');
371    my @tags = split ' ', $q->param('tags');
372    $self->_bookmarks->add({
373        uri   => $uri,
374        title => $title,
375        tags  => \@tags,
376    });
377
378=begin
379
380    my $location = URI->new($q->url);
381    $location->query_form(uri => $uri) if defined $q->url_param('uri');
382    $location->fragment('updated');
383
384=cut
385
386    # return to the form
387    $self->header_type('redirect');
388    $self->header_props(
389        -uri => $ENV{REQUEST_URI},
390        -status => 303,
391    );
392}
393
3941;
Note: See TracBrowser for help on using the repository browser.