source: bookmarks/trunk/lib/Bookmarks/Controller.pm @ 104

Last change on this file since 104 was 100, checked in by peter, 9 years ago

set the include path for the individual bookmark form template

File size: 6.7 KB
Line 
1package Bookmarks::Controller;
2
3use Moose;
4
5use Encode;
6use HTTP::Date qw{time2str str2time};
7use JSON;
8use Bookmarks;
9use Bookmarks::List;
10use URI;
11use Template;
12
13has dbname => (
14    is => 'ro',
15    required => 1,
16);
17has bookmarks => (
18    is => 'ro',
19    handles => [qw{get_bookmark}],
20    builder => '_build_bookmarks',
21    lazy => 1,
22);
23has base_uri => (
24    is => 'ro',
25    builder => '_build_base_uri',
26    lazy => 1,
27);
28has request => (
29    is => 'rw',
30);
31
32sub _build_bookmarks {
33    my $self = shift;
34    return Bookmarks->new({
35        dbname   => $self->dbname,
36        base_uri => $self->base_uri,
37    });
38}
39
40sub _build_base_uri {
41    my $self = shift;
42    my $url = $self->request->base;
43
44    $url .= '/' unless $url =~ m{/$};
45    return URI->new($url);
46}
47
48sub find_or_new {
49    my $self = shift;
50
51    my $bookmark = $self->bookmarks->get_bookmark({ uri => $self->request->param('uri') });
52    if ($bookmark) {
53        # redirect to the view of the existing bookmark
54        return [301, [Location => $bookmark->bookmark_uri], []];
55    } else {
56        # bookmark was not found; show the form to create a new bookmark
57        require File::Basename;
58        my $template = Template->new({ INCLUDE_PATH => File::Basename::dirname($INC{'Bookmarks/Controller.pm'}) });
59        $template->process(
60            'bookmark.tt',
61            { 
62                bookmark => {
63                    uri   => $self->request->param('uri'),
64                    title => $self->request->param('title') || '',
65                },
66            },
67            \my $output,
68        );
69        return [404, ['Content-Type' => 'text/html; charset=UTF-8'], [$output]];
70    }
71}
72
73sub list {
74    my $self = shift;
75
76    # list all the bookmarks
77    my $mtime = $self->bookmarks->get_last_modified_time;
78
79    my $format = $self->request->param('format') || 'html';
80
81    my @tags = grep { $_ ne '' } $self->request->param('tag');
82    my $query = $self->request->param('q');
83    my $limit = $self->request->param('limit');
84    my $offset = $self->request->param('offset');
85
86    my $list = Bookmarks::List->new({
87        bookmarks => $self->bookmarks,
88        search    => $self->bookmarks->search({
89            query  => $query,
90            tags   => \@tags,
91            limit  => $limit,
92            offset => $offset,
93        }),
94    });
95
96    my $as_format = "as_$format";
97    if (!$list->meta->has_method($as_format)) {
98        return [406, ['Content-Type' => 'text/plain; charset=UTF-8'], [qq{"$format" is not a supported format}]];
99    }
100    return $list->$as_format;
101}
102
103sub feed {
104    my $self = shift;
105
106    my $query = $self->request->param('q');
107    my @tags = grep { $_ ne '' } $self->request->param('tag');
108
109    # construct a feed from the most recent 12 bookmarks
110    my $list = Bookmarks::List->new({
111        bookmarks => $self->bookmarks,
112        search    => $self->bookmarks->search({ query => $query, tags => \@tags, limit => 12 }),
113    });
114    return $list->as_atom;
115}
116
117# returns 1 if there is an If-Modified-Since header and it is newer than the given $mtime
118# returns 0 if there is an If-Modified-Since header but the $mtime is newer
119# returns undef if there is no If-Modified-Since header
120sub _request_is_newer_than {
121    my $self = shift;
122    my $mtime = shift;
123
124    # check If-Modified-Since header to return cache response
125    if ($self->request->env->{HTTP_IF_MODIFIED_SINCE}) {
126        my $cache_time = str2time($self->request->env->{HTTP_IF_MODIFIED_SINCE});
127        return $mtime <= $cache_time ? 1 : 0;
128    } else {
129        return;
130    }
131}
132
133sub view {
134    my ($self, $id) = @_;
135
136    my $format = $self->request->param('format') || 'html';
137
138    my $bookmark = $self->get_bookmark({ id => $id });
139    if ($bookmark) {
140        return [304, [], []] if $self->_request_is_newer_than($bookmark->mtime);
141
142        my $last_modified = time2str($bookmark->mtime);
143       
144        if ($format eq 'json') {
145            my $json = decode_utf8(JSON->new->utf8->convert_blessed->encode($bookmark->to_hashref));
146            return [200, ['Content-Type' => 'application/json; charset=UTF-8', 'Last-Modified' => $last_modified], [$json]];
147        } else {
148            # display the bookmark form for this bookmark
149            require File::Basename;
150            my $template = Template->new({ INCLUDE_PATH => File::Basename::dirname($INC{'Bookmarks/Controller.pm'}) });
151            $template->process(
152                'bookmark.tt',
153                { bookmark => $bookmark },
154                \my $output,
155            );
156            return [200, ['Content-Type' => 'text/html; charset=UTF-8', 'Last-Modified' => $last_modified], [$output]];
157        }
158    } else {
159        return [404, ['Content-Type' => 'text/plain; charset=UTF-8'], ["Bookmark $id not found"]];
160    }
161}
162
163sub view_field {
164    my ($self, $id, $field) = @_;
165
166    my $bookmark = $self->get_bookmark({ id => $id });
167    if ($bookmark) {
168        return [304, [], []] if $self->_request_is_newer_than($bookmark->mtime);
169
170        # check whether the requested field is part of the bookmark
171        if (!$bookmark->meta->has_attribute($field)) {
172            return [404, ['Content-Type' => 'text/plain; charset=UTF-8'], [qq{"$field" is not a valid bookmark data field}]];
173        }
174
175        # respond with just the requested field as plain text
176        my $value = $bookmark->$field;
177        my $last_modified = time2str($bookmark->mtime);
178        return [200, ['Content-Type' => 'text/plain; charset=UTF-8', 'Last-Modified' => $last_modified], [ref $value eq 'ARRAY' ? join(' ', @{ $value }) : $value]];
179    } else {
180        return [404, ['Content-Type' => 'text/plain; charset=UTF-8'], ["Bookmark $id not found"]];
181    }
182}
183
184sub create_and_redirect {
185    my $self = shift;
186
187    my $uri   = $self->request->param('uri');
188    my $title = $self->request->param('title');
189    my @tags  = split ' ', $self->request->param('tags');
190
191    my $bookmark = $self->bookmarks->add({
192        uri   => $uri,
193        title => $title,
194        tags  => \@tags,
195    });
196
197    #TODO: not RESTful; the proper RESTful response would be a 201
198    return [303, ['Location' => $bookmark->bookmark_uri->canonical], []];
199}
200
201sub update_and_redirect {
202    my $self = shift;
203    my $id = shift;
204
205    my $bookmark = $self->bookmarks->get_bookmark({ id => $id });
206    if ($bookmark) {
207        # update the URI, title, and tags
208        $bookmark->uri($self->request->param('uri'));
209        $bookmark->title($self->request->param('title'));
210        $bookmark->tags([ split ' ', $self->request->param('tags') || '' ]);
211
212        # write to the database
213        $bookmark->update;
214
215        #TODO: not RESTful; proper response would be a 200
216        return [303, ['Location' => $bookmark->bookmark_uri->canonical], []];
217    } else {
218        return [404, ['Content-Type' => 'text/plain; charset=UTF-8'], ["Bookmark $id not found"]];
219    }
220}
221
2221;
Note: See TracBrowser for help on using the repository browser.