source: bookmarks/trunk/BookmarkController.pm @ 59

Last change on this file since 59 was 59, checked in by peter, 11 years ago
  • converted app.psgi from using a CGI::Application::Dispatch dispatcher to a Path::Router dispatcher
  • created a more pure PSGI BookmarkController to replace the CGI::Application-based BookmarkApp
  • added an access log to the start script
File size: 12.0 KB
Line 
1package BookmarkController;
2use Moose;
3
4use Encode;
5use HTTP::Date qw{time2isoz time2iso time2str str2time};
6use JSON;
7use Bookmarks;
8use URI;
9use Template;
10
11has bookmarks => (
12    is => 'rw',
13    handles => [qw{get_bookmark}],
14);
15has base_uri => (
16    is => 'ro',
17    builder => '_build_base_uri',
18    lazy => 1,
19);
20has request => (
21    is => 'ro',
22);
23
24sub _build_base_uri {
25    my $self = shift;
26    my $url = $self->request->base;
27
28    $url .= '/' unless $url =~ m{/$};
29    return URI->new($url);
30}
31
32sub _get_list_links {
33    my $self = shift;
34    my ($self_type, $query) = @_;
35    my @links = (
36        {
37            text => 'JSON',
38            type => 'application/json',
39            query => {
40                %$query,
41                format => 'json',
42            },
43        },
44        {
45            text => 'XBEL',
46            type => 'application/xml',
47            query => {
48                %$query,
49                format => 'xbel',
50            },
51        },
52        {
53            text => 'Atom',
54            type => 'application/atom+xml',
55            path => 'feed',
56            query => {
57                %$query,
58            },
59        },
60        {
61            text => 'CSV',
62            type => 'text/csv',
63            query => {
64                %$query,
65                format => 'csv',
66            },
67        },
68        {
69            text => 'URI List',
70            type => 'text/uri-list',
71            query => {
72                %$query,
73                format => 'text',
74            },
75        },
76        {
77            text => 'HTML',
78            type => 'text/html',
79            query => {
80                %$query,
81            },
82        },
83    );
84
85    for my $link (@links) {
86        $link->{rel}  = $link->{type} eq $self_type ? 'self' : 'alternate';
87        $link->{href} = URI->new_abs($link->{path} || '', $self->base_uri);
88        $link->{href}->query_form($link->{query});
89    }
90
91    return @links;
92}
93
94sub find_or_new {
95    my $self = shift;
96
97    my $bookmark = $self->bookmarks->get_bookmark({ uri => $self->request->param('uri') });
98    if ($bookmark) {
99        # redirect to the view of the existing bookmark
100        return [301, [Location => $bookmark->bookmark_uri], []];
101    } else {
102        # bookmark was not found; show the form to create a new bookmark
103        my $template = Template->new;
104        $template->process(
105            'bookmark.tt',
106            {
107                uri   => $self->request->param('uri'),
108                title => $self->request->param('title') || '',
109            },
110            \my $output,
111        );
112        return [404, ['Content-Type' => 'text/html; charset=UTF-8'], [$output]];
113    }
114}
115
116sub list {
117    my $self = shift;
118
119    # list all the bookmarks
120    my $mtime = $self->bookmarks->get_last_modified_time;
121
122    my $format = $self->request->param('format') || 'html';
123
124    my @tags = grep { $_ ne '' } $self->request->param('tag');
125    my $query = $self->request->param('q');
126    my $limit = $self->request->param('limit');
127    my $offset = $self->request->param('offset');
128    my @resources = $self->bookmarks->get_bookmarks({
129        query  => $query,
130        tag    => \@tags,
131        limit  => $limit,
132        offset => $offset,
133    });
134    my @all_tags = $self->bookmarks->get_tags({ selected => $tags[0] });
135    my @cotags = $self->bookmarks->get_cotags({
136        query  => $query,
137        tag    => \@tags,
138    });
139   
140    my $title = 'Bookmarks' . (@tags ? " tagged as " . join(' & ', @tags) : '') . ($query ? " matching '$query'" : '');
141
142    if ($format eq 'json') {
143        my $json = decode_utf8(
144            JSON->new->utf8->convert_blessed->encode({
145                bookmarks => \@resources,
146            })
147        );
148        return [200, ['Content-Type' => 'application/json; charset=UTF-8'], [$json]];
149    } elsif ($format eq 'xbel') {
150        require XML::XBEL;
151        #TODO: conditional support; if XML::XBEL is not present, return a 5xx response
152
153        my $xbel = XML::XBEL->new;
154
155        $xbel->new_document({
156            title => $title,
157        });
158
159        for my $bookmark (@resources) {
160            my $cdatetime = time2isoz $bookmark->ctime;
161            my $mdatetime = time2isoz $bookmark->mtime;
162            # make the timestamps W3C-correct
163            s/ /T/ foreach ($cdatetime, $mdatetime);
164
165            $xbel->add_bookmark({
166                href     => $bookmark->uri,
167                title    => $bookmark->title,
168                desc     => 'Tags: ' . join(', ', @{ $bookmark->tags }),
169                added    => $cdatetime,
170                #XXX: are we sure that modified is the mtime of the bookmark or the resource?
171                modified => $mdatetime,
172            });
173        }
174
175        return [200, ['Content-Type' => 'application/xml; charset=UTF-8'], [$xbel->toString]];
176    } elsif ($format eq 'text') {
177        my $text = join '', 
178            map {
179                sprintf "# %s\n# Tags: %s\n%s\n",
180                $_->title,
181                join(', ', @{ $_->tags }), 
182                $_->uri
183            } @resources;
184        return [200, ['Content-Type' => 'text/uri-list; charset=UTF-8'], [$text]];
185    } elsif ($format eq 'csv') {
186        require Text::CSV::Encoded;
187        my $csv = Text::CSV::Encoded->new({ encoding_out => 'utf8' });
188        my $text = qq{id,uri,title,tags,ctime,mtime\n};
189        for my $bookmark (@resources) {
190            my $success = $csv->combine(
191                $bookmark->id,
192                $bookmark->uri,
193                $bookmark->title,
194                join(' ', @{ $bookmark->tags }),
195                $bookmark->ctime,
196                $bookmark->mtime,
197            );
198            $text .= $csv->string . "\n" if $success;
199        }
200
201        # include the local timestamp in the attchment filename
202        my $dt = time2iso;
203        $dt =~ s/[^\d]//g;
204
205        my $filename = sprintf(
206            'bookmarks-%s-%s.csv',
207            join('_', @tags),
208            $dt,
209        );
210
211        return [200, ['Content-Type' => 'text/csv; charset=UTF-8', 'Content-Disposition' => sprintf('attachement; filename="%s"', $filename)], [$text]];
212    } else {
213        my $template = Template->new;
214
215        $template->process(
216            'list.tt',
217            {
218                base_url     => $self->base_uri,
219                title        => $title,
220                query        => $query,
221                selected_tag => $tags[0],
222                search_tags  => \@tags,
223                links        => [ $self->_get_list_links('text/html', { q => $query, tag => \@tags }) ],
224                all_tags     => \@all_tags,
225                cotags       => \@cotags,
226                resources    => \@resources,
227            },
228            \my $output,
229        );
230        return [200, ['Content-Type' => 'text/html; charset=UTF-8'], [$output]];
231    }
232}
233
234sub feed {
235    my $self = shift;
236
237    my $query = $self->request->param('q');
238    my @tags = grep { $_ ne '' } $self->request->param('tag');
239    my $title = 'Bookmarks' . (@tags ? " tagged as " . join(' & ', @tags) : '');
240
241    require XML::Atom;
242    $XML::Atom::DefaultVersion = "1.0";
243
244    require XML::Atom::Feed;
245    require XML::Atom::Entry;
246    require XML::Atom::Link;
247    require XML::Atom::Category;
248
249    my $feed = XML::Atom::Feed->new;
250    $feed->title($title);
251
252    my $feed_uri = URI->new_abs('feed', $self->base_uri);
253    $feed_uri->query_form(tag => \@tags);
254    $feed->id($feed_uri->canonical);
255
256    for my $link ($self->_get_list_links('application/atom+xml', { q => $query, tag => \@tags })) {
257        my $atom_link = XML::Atom::Link->new;
258        $atom_link->type($link->{type});
259        $atom_link->rel($link->{rel});
260        $atom_link->href($link->{href}->canonical);
261        $feed->add_link($atom_link);
262    }
263
264    # construct a feed from the most recent 12 bookmarks
265    for my $bookmark ($self->bookmarks->get_bookmarks({ query => $query, tag => \@tags, limit => 12 })) {
266        my $entry = XML::Atom::Entry->new;
267        $entry->id($bookmark->bookmark_uri->canonical);
268        $entry->title($bookmark->title);
269       
270        my $link = XML::Atom::Link->new;
271        $link->href($bookmark->uri);
272        $entry->add_link($link);
273       
274        $entry->summary('Tags: ' . join(', ', @{ $bookmark->tags }));
275
276        my $cdatetime = time2isoz $bookmark->ctime;
277        my $mdatetime = time2isoz $bookmark->mtime;
278        # make the timestamp W3C-correct
279        s/ /T/ foreach ($cdatetime, $mdatetime);
280        $entry->published($cdatetime);
281        $entry->updated($mdatetime);
282       
283        for my $tag (@{ $bookmark->tags }) {
284            my $category = XML::Atom::Category->new;
285            $category->term($tag);
286            $entry->add_category($category);
287        }
288
289        $feed->add_entry($entry);
290    }
291
292    return [200, ['Content-Type' => 'application/atom+xml; charset=UTF-8'], [$feed->as_xml]];
293}
294
295sub view {
296    my ($self, $id) = @_;
297
298    my $format = $self->request->param('format') || 'html';
299
300    my $bookmark = $self->get_bookmark({ id => $id });
301    if ($bookmark) {
302        # check If-Modified-Since header to return cache response
303        if ($self->request->env->{HTTP_IF_MODIFIED_SINCE}) {
304            my $cache_time = str2time($self->request->env->{HTTP_IF_MODIFIED_SINCE});
305            if ($bookmark->mtime <= $cache_time) {
306                return [304, [], []];
307            }
308        }
309        my $last_modified = time2str($bookmark->mtime);
310       
311        if ($format eq 'json') {
312            my $json = decode_utf8(JSON->new->utf8->convert_blessed->encode($bookmark));
313            return [200, ['Content-Type' => 'application/json; charset=UTF-8', 'Last-Modified' => $last_modified], [$json]];
314        } else {
315            # display the bookmark form for this bookmark
316            $bookmark->{exists} = 1;
317            $bookmark->{created} = "Created " . localtime($bookmark->ctime);
318            $bookmark->{created} .= '; Updated ' . localtime($bookmark->mtime) unless $bookmark->ctime == $bookmark->mtime;
319            my $template = Template->new;
320            $template->process(
321                'bookmark.tt',
322                $bookmark,
323                \my $output,
324            );
325            return [200, ['Content-Type' => 'text/html; charset=UTF-8', 'Last-Modified' => $last_modified], [$output]];
326        }
327    } else {
328        return [404, ['Content-Type' => 'text/plain; charset=UTF-8'], ["Boomark $id not found"]];
329    }
330}
331
332sub view_field {
333    my ($self, $id, $field) = @_;
334
335    my $bookmark = $self->bookmarks->get_bookmark({ id => $id });
336    if ($bookmark) {
337        # respond with just the requested field as plain text
338        my $value = eval { $bookmark->$field };
339        if ($@) {
340            if ($@ =~ /Can't locate object method/) {
341                return [404, ['Content-Type' => 'text/plain; charset=UTF-8'], [qq{"$field" is not a valid bookmark data field}]];
342            } else {
343                die $@;
344            }
345        }
346        return [200, ['Content-Type' => 'text/plain; charset=UTF-8'], [ref $value eq 'ARRAY' ? join(' ', @{ $value }) : $value]];
347    } else {
348        return [404, ['Content-Type' => 'text/plain; charset=UTF-8'], ["Boomark $id not found"]];
349    }
350}
351
352sub create {
353    my $self = shift;
354
355    my $uri   = $self->request->param('uri');
356    my $title = $self->request->param('title');
357    my @tags  = split ' ', $self->request->param('tags');
358
359    my $bookmark = $self->bookmarks->add({
360        uri   => $uri,
361        title => $title,
362        tags  => \@tags,
363    });
364
365    #TODO: not RESTful; the proper RESTful response would be a 201
366    return [303, ['Location' => $bookmark->bookmark_uri->canonical], []];
367}
368
369sub edit {
370    my $self = shift;
371    my $id = shift;
372
373    my $bookmark = $self->bookmarks->get_bookmark({ id => $id });
374    if ($bookmark) {
375        # update the URI, title, and tags
376        $bookmark->uri($self->request->param('uri'));
377        $bookmark->title($self->request->param('title'));
378        $bookmark->tags([ split ' ', $self->request->param('tags') || '' ]);
379
380        # write to the database
381        $self->bookmarks->update($bookmark);
382
383        #TODO: not RESTful; proper response would be a 200
384        return [303, ['Location' => $bookmark->bookmark_uri->canonical], []];
385    } else {
386        return [404, ['Content-Type' => 'text/plain; charset=UTF-8'], ["Boomark $id not found"]];
387    }
388}
389
3901;
Note: See TracBrowser for help on using the repository browser.