File Coverage

blib/lib/WebService/Google/Reader.pm
Criterion Covered Total %
statement 34 36 94.4
branch n/a
condition n/a
subroutine 12 12 100.0
pod n/a
total 46 48 95.8


line stmt bran cond sub pod time code
1             package WebService::Google::Reader;
2              
3 2     2   35824 use strict;
  2         4  
  2         68  
4 2     2   7 use warnings;
  2         2  
  2         58  
5 2     2   942 use parent qw(Class::Accessor::Fast);
  2         563  
  2         10  
6              
7 2     2   6092 use Carp qw(croak);
  2         4  
  2         123  
8 2     2   1144 use HTTP::Request::Common qw(GET POST);
  2         51695  
  2         168  
9 2     2   1413 use LWP::UserAgent;
  2         43610  
  2         57  
10 2     2   1232 use JSON;
  2         18190  
  2         9  
11 2     2   288 use URI;
  2         4  
  2         42  
12 2     2   7 use URI::Escape;
  2         2  
  2         100  
13 2     2   858 use URI::QueryParam;
  2         1073  
  2         48  
14              
15 2     2   708 use WebService::Google::Reader::Constants;
  2         2  
  2         190  
16 2     2   701 use WebService::Google::Reader::Feed;
  0            
  0            
17             use WebService::Google::Reader::ListElement;
18              
19             our $VERSION = '0.23';
20             $VERSION = eval $VERSION;
21              
22             __PACKAGE__->mk_accessors(qw(
23             appid appkey auth compress error host password response scheme token ua
24             username
25             ));
26              
27             sub new {
28             my ($class, %params) = @_;
29              
30             my $self = bless { %params }, $class;
31              
32             croak q('host' is required) unless $self->host;
33             my $host = $self->host;
34             $host = "http://$host" unless $host =~ m[^https?://];
35             $host =~ s[/+$][];
36             $self->host($host);
37              
38             if ($host =~ /(^|\.)inoreader\.com$/i) {
39             croak q('appid' and 'appkey' are required by inoreader)
40             unless defined $self->appid and defined $self->appkey;
41             }
42              
43             my $ua = $params{ua};
44             unless (ref $ua and $ua->isa(q(LWP::UserAgent))) {
45             $ua = LWP::UserAgent->new(
46             agent => __PACKAGE__.'/'.$VERSION,
47             );
48             $self->ua($ua);
49             }
50              
51             $self->compress(1);
52             $self->debug(0);
53             for my $accessor (qw( compress debug )) {
54             $self->$accessor($params{$accessor}) if exists $params{$accessor};
55             }
56              
57             $ua->default_header(accept_encoding => 'gzip,deflate')
58             if $self->compress;
59              
60             $self->scheme($params{secure} || $params{https} ? 'https' : 'http');
61              
62             return $self;
63             }
64              
65             sub debug {
66             my ($self, $val) = @_;
67             return $self->{debug} unless 2 == @_;
68              
69             my $ua = $self->ua;
70             if ($val) {
71             my $dump_sub = sub { $_[0]->dump(maxlength => 0); return };
72             $ua->set_my_handler(request_send => $dump_sub);
73             $ua->set_my_handler(response_done => $dump_sub);
74             }
75             else {
76             $ua->set_my_handler(request_send => undef);
77             $ua->set_my_handler(response_done => undef);
78             }
79              
80             return $self->{debug} = $val;
81             }
82              
83             ## Feeds
84              
85             sub feed { shift->_feed(feed => shift, @_) }
86             sub tag { shift->_feed(tag => shift, @_) }
87             sub state { shift->_feed(state => shift, @_) }
88              
89             sub shared { shift->state(broadcast => @_) }
90             sub starred { shift->state(starred => @_) }
91             sub liked { shift->state(like => @_) }
92             sub unread {
93             shift->state(
94             'reading-list', exclude => { state => 'read' }, @_
95             );
96             }
97              
98             sub search {
99             my ($self, $query, %params) = @_;
100              
101             $self->_login or return;
102             $self->_token or return;
103              
104             my $uri = URI->new($self->host . SEARCH_ITEM_IDS_PATH);
105              
106             my %fields = (num => $params{results} || 1000);
107              
108             my @types = grep { exists $params{$_} } qw(feed state tag);
109             for my $type (@types) {
110             push @{$fields{s}}, _encode_type($type, $params{$type});
111             }
112              
113             $uri->query_form({ q => $query, %fields, output => 'json' });
114              
115             my $req = HTTP::Request->new(GET => $uri);
116             my $res = $self->_request($req) or return;
117              
118             my @ids = do {
119             my $ref = eval { from_json($res->decoded_content) } or do {
120             $self->error("Failed to parse JSON response: $@");
121             return;
122             };
123             map { $_->{id} } @{$ref->{results}};
124             };
125             return unless @ids;
126             if (my $order = $params{order} || $params{sort}) {
127             @ids = reverse @ids if 'asc' eq $order;
128             }
129              
130             my $feed = (__PACKAGE__.'::Feed')->new(
131             request => $req, ids => \@ids, count => $params{count} || 40,
132             );
133             return $self->more($feed);
134             }
135              
136             sub more {
137             my ($self, $feed) = @_;
138              
139             my $req;
140             if (defined $feed->ids) {
141             my @ids = splice @{$feed->ids}, 0, $feed->count;
142             return unless @ids;
143              
144             my $uri = URI->new($self->host . STREAM_ITEMS_CONTENTS_PATH);
145             $req = POST $uri, [ output => 'atom', map { (i => $_) } @ids ];
146             }
147             elsif ($feed->elem) {
148             return unless defined $feed->continuation;
149             return if $feed->entries < $feed->count;
150             $req = $feed->request;
151             my $prev_continuation = $req->uri->query_param('c') || '';
152             return if $feed->continuation eq $prev_continuation;
153             $req->uri->query_param(c => $feed->continuation);
154             }
155             elsif ($req = $feed->request) {
156             # Initial request.
157             }
158             else { return }
159              
160             my $res = $self->_request($req) or return;
161              
162             $feed->init(Stream => $res->decoded_content(ref => 1)) or return;
163             return $feed;
164             }
165              
166             *previous = *previous = *next = *next = \&more;
167              
168             ## Lists
169              
170             sub tags { $_[0]->_list($_[0]->host . LIST_TAGS_PATH) }
171             sub feeds { $_[0]->_list($_[0]->host . LIST_SUBS_PATH) }
172             sub preferences { $_[0]->_list($_[0]->host . LIST_PREFS_PATH) }
173             sub counts { $_[0]->_list($_[0]->host . LIST_COUNTS_PATH) }
174             sub userinfo { $_[0]->_list($_[0]->host . LIST_USER_INFO_PATH) }
175              
176             ## Edit tags
177              
178             sub edit_tag { shift->_edit_tag(tag => @_) }
179             sub edit_state { shift->_edit_tag(state => @_) }
180             sub share_tag { shift->edit_tag(_listify(\@_), share => 1) }
181             sub unshare_tag { shift->edit_tag(_listify(\@_), unshare => 1) }
182             sub share_state { shift->edit_state(_listify(\@_), share => 1) }
183             sub unshare_state { shift->edit_state(_listify(\@_), unshare => 1) }
184             sub delete_tag { shift->edit_tag(_listify(\@_), delete => 1) }
185             sub mark_read_tag { shift->mark_read(tag => _listify(\@_)) }
186             sub mark_read_state { shift->mark_read(state => _listify(\@_)) }
187              
188             sub rename_feed_tag {
189             my ($self, $old, $new) = @_;
190              
191             my @tagged;
192             my @feeds = $self->feeds or return;
193              
194             # Get the list of subs which are associated with the tag to be renamed.
195             FEED:
196             for my $feed (@feeds) {
197             for my $cat ($self->categories) {
198             for my $o ('ARRAY' eq ref $old ? @$old : ($old)) {
199             if ($o eq $cat->label or $o eq $cat->id) {
200             push @tagged, $feed->id;
201             next FEED;
202             }
203             }
204             }
205             }
206              
207             $_ = [ _encode_type(tag => $_) ] for ($old, $new);
208              
209             return $self->edit_feed(\@tagged, tag => $new, untag => $old);
210             }
211              
212             sub rename_entry_tag {
213             my ($self, $old, $new) = @_;
214              
215             for my $o ('ARRAY' eq ref $old ? @$old : ($old)) {
216             my $feed = $self->tag($o) or return;
217             do {
218             $self->edit_entry(
219             [ $feed->entries ], tag => $new, untag => $old
220             ) or return;
221             } while ($self->feed($feed));
222             }
223              
224             return 1;
225             }
226              
227             sub rename_tag {
228             my $self = shift;
229             return unless $self->rename_tag_feed(@_);
230             return unless $self->rename_tag_entry(@_);
231             return $self->delete_tags(shift);
232             }
233              
234             ## Edit feeds
235              
236             sub edit_feed {
237             my ($self, $sub, %params) = @_;
238              
239             $self->_login or return;
240             $self->_token or return;
241              
242             my $url = $self->host . EDIT_SUB_PATH;
243              
244             my %fields;
245             for my $s ('ARRAY' eq ref $sub ? @$sub : ($sub)) {
246             if (__PACKAGE__.'::Feed' eq ref $s) {
247             my $id = $s->id or next;
248             $id =~ s[^(?:user|webfeed|tag:google\.com,2005:reader/)][];
249             $id =~ s[\?.*][];
250             push @{$fields{s}}, $id;
251             }
252             else {
253             push @{$fields{s}}, _encode_type(feed => $s);
254             }
255             }
256             return 1 unless @{$fields{s} || []};
257              
258             if (defined(my $title = $params{title})) {
259             $fields{t} = $title;
260             }
261              
262             if (grep { exists $params{$_} } qw(subscribe add)) {
263             $fields{ac} = 'subscribe';
264             }
265             elsif (grep { exists $params{$_} } qw(unsubscribe remove)) {
266             $fields{ac} = 'unsubscribe';
267             }
268             else {
269             $fields{ac} = 'edit';
270             }
271              
272             # Add a tag or state.
273             for my $t (qw(tag state)) {
274             next unless exists $params{$t};
275             defined(my $p = $params{$t}) or next;
276             for my $a ('ARRAY' eq ref $p ? @$p : ($p)) {
277             push @{$fields{a}}, _encode_type($t => $a);
278             }
279             }
280             # Remove a tag or state.
281             for my $t (qw(untag unstate)) {
282             next unless exists $params{$t};
283             defined(my $p = $params{$t}) or next;
284             for my $d ('ARRAY' eq ref $p ? @$p : ($p)) {
285             push @{$fields{r}}, _encode_type(substr($t, 2) => $d);
286             }
287             }
288              
289             return $self->_edit($url, %fields);
290             }
291              
292             sub tag_feed { shift->edit_feed(shift, tag => \@_) }
293             sub untag_feed { shift->edit_feed(shift, untag => \@_) }
294             sub state_feed { shift->edit_feed(shift, state => \@_) }
295             sub unstate_feed { shift->edit_feed(shift, unstate => \@_) }
296             sub subscribe { shift->edit_feed(_listify(\@_), subscribe => 1) }
297             sub unsubscribe { shift->edit_feed(_listify(\@_), unsubscribe => 1) }
298             sub mark_read_feed { shift->mark_read(feed => _listify(\@_)) }
299             sub rename_feed { $_[0]->edit_feed($_[1], title => $_[2]) }
300              
301             ## Edit entries
302              
303             sub edit_entry {
304             my ($self, $entry, %params) = @_;
305             return unless $entry;
306              
307             $self->_login or return;
308             $self->_token or return;
309              
310             my %fields = (ac => 'edit');
311             for my $e ('ARRAY' eq ref $entry ? @$entry : ($entry)) {
312             my $source = $e->source or next;
313             my $stream_id = $source->get_attr('gr:stream-id') or next;
314             push @{$fields{i}}, $e->id;
315             push @{$fields{s}}, $stream_id;
316             }
317             return 1 unless @{$fields{i} || []};
318              
319             my $url = $self->host . EDIT_ENTRY_TAG_PATH;
320              
321             # Add a tag or state.
322             for my $t (qw(tag state)) {
323             next unless exists $params{$t};
324             defined(my $p = $params{$t}) or next;
325             for my $a ('ARRAY' eq ref $p ? @$p : ($p)) {
326             push @{$fields{a}}, _encode_type($t => $a);
327             }
328             }
329             # Remove a tag or state.
330             for my $t (qw(untag unstate)) {
331             next unless exists $params{$t};
332             defined(my $p = $params{$t}) or next;
333             for my $d ('ARRAY' eq ref $p ? @$p : ($p)) {
334             push @{$fields{r}}, _encode_type(substr($t, 2) => $d);
335             }
336             }
337              
338             return $self->_edit($url, %fields);
339             }
340              
341             sub tag_entry { shift->edit_entry(shift, tag => \@_) }
342             sub untag_entry { shift->edit_entry(shift, untag => \@_) }
343             sub state_entry { shift->edit_entry(shift, state => \@_) }
344             sub unstate_entry { shift->edit_entry(shift, unstate => \@_) }
345             sub share_entry { shift->edit_entry(_listify(\@_), state => 'broadcast') }
346             sub unshare_entry { shift->edit_entry(_listify(\@_), unstate => 'broadcast') }
347             sub star_entry { shift->edit_entry(_listify(\@_), state => 'starred') }
348             sub unstar_entry { shift->edit_entry(_listify(\@_), unstate => 'starred') }
349             sub mark_read_entry { shift->edit_entry(_listify(\@_), state => 'read') }
350             sub like_entry { shift->edit_entry(_listify(\@_), state => 'like') }
351             sub unlike_entry { shift->edit_entry(_listify(\@_), unstate => 'like') }
352              
353             # Create some aliases.
354             for (qw(star unstar like unlike)) {
355             no strict 'refs';
356             *$_ = \&{$_.'_entry'};
357             }
358              
359             ## Miscellaneous
360              
361             sub mark_read {
362             my ($self, %params) = @_;
363              
364             $self->_login or return;
365             $self->_token or return;
366              
367             my %fields;
368             my @types = grep { exists $params{$_} } qw(feed state tag);
369             for my $type (@types) {
370             push @{$fields{s}}, _encode_type($type, $params{$type});
371             }
372              
373             return $self->_edit($self->host . EDIT_MARK_READ_PATH, %fields);
374             }
375              
376             sub edit_preference {
377             my ($self, $key, $val) = @_;
378              
379             $self->_login or return;
380             $self->_token or return;
381              
382             return $self->_edit($self->host . EDIT_PREF_PATH, k => $key, v => $val);
383             }
384              
385             sub opml {
386             my ($self) = @_;
387              
388             $self->_login or return;
389              
390             my $res = $self->_request(GET($self->host . EXPORT_SUBS_PATH)) or return;
391              
392             return $res->decoded_content;
393             }
394              
395             sub ping {
396             my ($self) = @_;
397             my $res = $self->_request(GET($self->host . PING_PATH)) or return;
398              
399             return 1 if 'OK' eq $res->decoded_content;
400              
401             $self->error('Ping failed: '. $res->decoded_content);
402             return;
403             }
404              
405             ## Private interface
406              
407             sub _request {
408             my ($self, $req, $count) = @_;
409              
410             return if $count and 3 <= $count;
411              
412             # Assume all POST requests are secure.
413             if ('POST' eq $req->method) {
414             $req->uri->scheme('https');
415             }
416             elsif ('GET' eq $req->method and 'https' ne $req->uri->scheme) {
417             $req->uri->scheme($self->scheme);
418             }
419              
420             $req->uri->query_param(ck => time * 1000);
421             $req->uri->query_param(client => $self->ua->agent);
422              
423             $req->header(AppId => $self->appid, AppKey => $self->appkey)
424             if defined $self->appid and defined $self->appkey;
425             $req->header(authorization => 'GoogleLogin auth=' . $self->auth)
426             if $self->auth;
427              
428             my $res = $self->ua->request($req);
429             $self->response($res);
430             if ($res->is_error) {
431             # Need fresh tokens.
432             if (401 == $res->code and $res->message =~ /^Token /) {
433             print "Stale Auth token- retrying\n" if $self->debug;
434             $self->_login(1) or return;
435             return $self->_request($req, ++$count);
436             }
437             elsif ($res->header('X-Reader-Google-Bad-Token')) {
438             print "Stale T token- retrying\n" if $self->debug;
439             $self->_token(1) or return;
440              
441             # Replace the T token in the url-encoded content.
442             my $uri = URI->new;
443             $uri->query($req->content);
444             $uri->query_param(T => $self->token);
445             $req->content($uri->query);
446              
447             return $self->_request($req, ++$count);
448             }
449              
450             $self->error(join ' - ',
451             'Request failed', $res->status_line, $res->header('title')
452             );
453             return;
454             }
455              
456             # Reset the error from previous requests.
457             $self->error(undef);
458              
459             return $res;
460             }
461              
462             sub _login {
463             my ($self, $force) = @_;
464              
465             return 1 if $self->_public;
466             return 1 if $self->auth and not $force;
467              
468             my $uri = URI->new($self->host . LOGIN_PATH);
469             $uri->query_form(
470             service => 'reader',
471             Email => $self->username,
472             Passwd => $self->password,
473             source => $self->ua->agent,
474             );
475             my $res = $self->_request(POST($uri)) or return;
476              
477             my $content = $res->decoded_content;
478             my ($auth) = $content =~ m[ ^Auth=(.*)$ ]mx;
479             unless ($auth) {
480             $self->error('Failed to find Auth token');
481             return;
482             }
483             $self->auth($auth);
484              
485             return 1;
486             }
487              
488             sub _token {
489             my ($self, $force) = @_;
490              
491             return 1 if $self->token and not $force;
492              
493             $self->_login($force) or return;
494              
495             my $uri = URI->new($self->host . TOKEN_PATH);
496             $uri->scheme('https');
497             my $res = $self->_request(GET($uri)) or return;
498              
499             return $self->token($res->decoded_content);
500             }
501              
502             sub _public {
503             return ! ($_[0]->username and $_[0]->password);
504             }
505              
506             sub _encode_type {
507             my ($type, $val, $escape) = @_;
508              
509             my @paths;
510             if ('feed' eq $type) { @paths = _encode_feed($val, $escape) }
511             elsif ('tag' eq $type) { @paths = _encode_tag($val) }
512             elsif ('state' eq $type) { @paths = _encode_state($val) }
513             elsif ('entry' eq $type) { @paths = _encode_entry($val) }
514             else { return }
515              
516             return wantarray ? @paths : shift @paths;
517             }
518              
519             sub _encode_feed {
520             my ($feed, $escape) = @_;
521              
522             my @paths;
523             for my $f ('ARRAY' eq ref $feed ? @$feed : ($feed)) {
524             my $path = ($escape ? uri_escape($f) : $f);
525             $path = "feed/$path"
526             if 'user/' ne substr $f, 0, 5 and 'feed/' ne substr $f, 0, 5;
527             push @paths, $path;
528             }
529              
530             return @paths;
531             }
532              
533             sub _encode_tag {
534             my ($tag) = @_;
535              
536             my @paths;
537             for my $t ('ARRAY' eq ref $tag ? @$tag : ($tag)) {
538             my $path = $t;
539             if ($t !~ m[ ^user/(?:-|\d{20})/ ]x) {
540             $path = "user/-/label/$t"
541             }
542             push @paths, $path;
543             }
544              
545             return @paths;
546             }
547              
548             sub _encode_state {
549             my ($state) = @_;
550              
551             my @paths;
552             for my $s ('ARRAY' eq ref $state ? @$state : ($state)) {
553             my $path = $s;
554             if ($s !~ m[ ^user/(?:-|\d{20})/ ]x) {
555             $path = "user/-/state/com.google/$s";
556             }
557             push @paths, $path;
558             }
559              
560             return @paths;
561             }
562              
563             sub _encode_entry {
564             my ($entry) = @_;
565              
566             my @paths;
567             for my $e ('ARRAY' eq ref $entry ? @$entry : ($entry)) {
568             my $path = $e;
569             if ('tag:google.com,2005:reader/item/' ne substr $e, 0, 32) {
570             $path = "tag:google.com,2005:reader/item/$e";
571             }
572             push @paths, $path;
573             }
574              
575             return @paths;
576             }
577              
578             sub _feed {
579             my ($self, $type, $val, %params) = @_;
580             return unless $val;
581              
582             $self->_login or return;
583              
584             my $path = $self->host . ($self->_public ? ATOM_PUBLIC_PATH : ATOM_PATH);
585             my $uri = URI->new($path . '/' . _encode_type($type, $val, 1));
586              
587             my %fields;
588             if (my $count = $params{count}) {
589             $fields{n} = $count;
590             }
591             if (my $start_time = $params{start_time}) {
592             $fields{ot} = $start_time;
593             }
594             if (my $order = $params{order} || $params{sort} || 'desc') {
595             # m = magic/auto; not really sure what that is
596             $fields{r} = 'desc' eq $order ? 'n' :
597             'asc' eq $order ? 'o' : $order;
598             }
599             if (defined(my $continuation = $params{continuation})) {
600             $fields{c} = $continuation;
601             }
602             if (my $ex = $params{exclude}) {
603             for my $x ('ARRAY' eq ref $ex ? @$ex : ($ex)) {
604             while (my ($xtype, $exclude) = each %$x) {
605             push @{$fields{xt}}, _encode_type($xtype, $exclude);
606             }
607             }
608             }
609              
610             $uri->query_form(\%fields);
611              
612             my $feed = (__PACKAGE__.'::Feed')->new(request => GET($uri), %params);
613             return $self->more($feed);
614             }
615              
616             sub _list {
617             my ($self, $url) = @_;
618              
619             $self->_login or return;
620              
621             my $uri = URI->new($url);
622             $uri->query_form({ $uri->query_form, output => 'json' });
623              
624             my $res = $self->_request(GET($uri)) or return;
625              
626             my $ref = eval { from_json($res->decoded_content) } or do {
627             $self->error("Failed to parse JSON response: $@");
628             return;
629             };
630              
631             # Remove an unecessary level of indirection.
632             my $aref = (grep { 'ARRAY' eq ref } values %$ref)[0] || [];
633              
634             for my $ref (@$aref) {
635             $ref = (__PACKAGE__.'::ListElement')->new($ref)
636             }
637              
638             return @$aref
639             }
640              
641             sub _edit {
642             my ($self, $url, %fields) = @_;
643             my $uri = URI->new($url);
644             my $req = POST($uri, [ %fields, T => $self->token ]);
645             my $res = $self->_request($req) or return;
646              
647             return 1 if 'OK' eq $res->decoded_content;
648              
649             # TODO: is there a standard error format which can be reliably parsed?
650             $self->error('Edit failed: '. $res->decoded_content);
651             return;
652             }
653              
654             sub _edit_tag {
655             my ($self, $type, $tag, %params) = @_;
656             return unless $tag;
657              
658             $self->_login or return;
659             $self->_token or return;
660              
661             my %fields = (s => [ _encode_type($type => $tag) ]);
662             return 1 unless @{$fields{s}};
663              
664             my $url;
665             if (grep { exists $params{$_} } qw(share public)) {
666             $url = $self->host . EDIT_TAG_SHARE_PATH;
667             $fields{pub} = 'true';
668             }
669             elsif (grep { exists $params{$_} } qw(unshare private)) {
670             $url = $self->host . EDIT_TAG_SHARE_PATH;
671             $fields{pub} = 'false';
672             }
673             elsif (grep { exists $params{$_} } qw(disable delete)) {
674             $url = $self->host . EDIT_TAG_DISABLE_PATH;
675             $fields{ac} = 'disable-tags';
676             }
677             else {
678             $self->error('Unknown action');
679             return;
680             }
681              
682             return $self->_edit($url, %fields);
683             }
684              
685             sub _states {
686             return qw(
687             read kept-unread fresh starred broadcast reading-list
688             tracking-body-link-used tracking-emailed tracking-item-link-used
689             tracking-kept-unread like
690             );
691             }
692              
693             sub _listify {
694             my ($aref) = @_;
695             return (1 == @$aref and 'ARRAY' eq ref $aref->[0]) ? @$aref : $aref;
696             }
697              
698              
699             1;
700              
701             __END__