skip invalid urls and crawl collection items
[ILL-Zotero-RT] / zotero.pl
1 #!/usr/bin/perl
2 use warnings;
3 use strict;
4
5 use LWP::Simple;
6 use XML::Simple;
7 use JSON;
8 use Data::Dump qw(dump);
9 use RT::Client::REST;
10 use URI::Escape;
11
12 use CouchDB;
13 use Digest::MD5 qw(md5_hex);
14
15 my $UserID = $ENV{UserID} || die "usage: UserID=1234 key=abcd $0";
16 my $key    = $ENV{key}    || die "key required";
17
18 my $FETCH  = $ENV{FETCH}  || 0;
19
20 my $db = CouchDB->new('10.60.0.92', 5984);
21 eval { $db->put("zotero_$UserID") }; # create user database
22 eval {
23         local $/ = undef;
24         my $view = <DATA>;
25         warn "# create $view";
26         $db->put("zotero_$UserID/_design/zotero" => decode_json $view)
27 };
28
29 eval { $db->put("rt") }; # create RT database
30
31 my @urls = map { "https://api.zotero.org/users/$UserID/$_?format=atom&content=json&order=dateModified&sort=desc" } qw( collections items );
32 # we don't need to fetch tags since we can generate using CouchDB views
33
34 my $url = shift @urls;
35
36 my $tree;
37 my $ticket_items;
38 my $items;
39
40 restart:
41
42 $url .= '&key=' . $key;
43
44 my $file = $UserID . '.' . md5_hex($url) . '.atom';
45 $FETCH = 1 if ! -e $file;
46
47 warn "# mirror $FETCH $url -> $file\n";
48 if ( $FETCH && mirror( $url => $file ) == RC_NOT_MODIFIED ) {
49         warn "not modified";
50 }
51
52 my $feed = eval { XMLin( $file ) };
53 if ( $! ) {
54         warn "ERROR $file $!\n";
55         goto skip_url;
56 }
57 #warn "# feed ",dump($feed);
58
59 sub link_to_id {
60         my $link = shift;
61         $link =~ s{.+/(items|collections)/}{}; # leave just ID
62         $link =~ s{\?.+}{};
63         return $link;
64 }
65
66 foreach my $entry ( keys %{ $feed->{entry} } ) {
67         warn "# entry $entry ",dump($entry);
68         my $id = link_to_id $entry;
69
70         my $item = $feed->{entry}->{$entry};
71         warn "# entry $entry ",dump($item);
72
73         foreach my $i ( 0 .. $#{ $item->{link} } ) {
74                 my $link = $item->{link}->[$i];
75                 warn "# link $id $i:",dump($link);
76
77                 $item->{link}->[$i]->{key} = link_to_id $link->{href};
78
79                 if ( $link->{rel} eq 'up' ) {
80                         push @{ $tree->{$key} }, $id;
81                 } elsif ( $link->{rel} eq 'self' && $link->{href} =~ m{/collections/} ) {
82                         warn "# get items in this collection";
83                         push @urls, "$link->{href}/items"; 
84                 }
85         }
86
87         if ( exists $item->{content} ) {
88                 my $type = ( grep { exists $item->{content}->{$_} } qw(zapi:type type) )[0];
89                 warn "# content has $type";
90
91                 $item->{zapi}->{etag} = $item->{content}->{'zapi:etag'} if exists $item->{content}->{'zapi:etag'};
92
93                 $type = $item->{zapi}->{type} = $item->{content}->{$type};
94
95                 if ( $type =~ m/json/ ) {
96
97                         my $json = $item->{content}->{content};
98                         warn "# $json\n";
99                         $json = $item->{content} = decode_json $json;
100                         warn "# json $id ", dump $json;
101
102                         foreach my $tag ( @{ $json->{tags} } ) {
103                                 $tag = $tag->{tag};
104                                 warn "# tag $id $tag\n";
105                                 next unless $tag =~ m/#(\d+)/; # XXX RT number in tag
106                                 push @{ $ticket_items->{$1} }, $id;
107                         }
108
109                 } else {
110                         warn "ERROR: $type not decoded!";
111                 }
112         }
113
114         foreach my $zapi ( grep { m/^zapi:/ } keys %$item ) {
115                 my $name = $zapi;
116                 $name =~ s/^zapi://;
117                 $item->{zapi}->{$name} = delete $item->{$zapi};
118         }
119
120         $items->{$id} = $item;
121
122         $db->modify( "zotero_$UserID/$id" => $item );
123
124 }
125
126 delete $feed->{entry};
127 warn "# feed without entry ",dump( $feed );
128
129 if ( my @next = map { $_->{href} } grep { $_->{rel} eq 'next' && $_->{type} eq 'application/atom+xml' } @{ $feed->{link} } ) {
130         warn "## next ",dump(@next);
131         $url = $next[0];
132         goto restart;
133 }
134
135 skip_url:
136
137 if ( $url = shift @urls ) {
138         warn "## next url $url";
139         goto restart;
140 }
141
142 warn "# tree ",dump( $tree );
143
144 warn "# ticket_items ",dump( $ticket_items );
145
146
147 my $rt = RT::Client::REST->new(
148         server => 'http://rt.rot13.org/rt',
149         timeout => 30,
150 );
151
152 $rt->login(username => $ENV{RT_USER}, password => $ENV{RT_PASSWORD});
153
154 foreach my $nr ( keys %$ticket_items ) {
155
156         my $ticket = eval { $rt->show(type => 'ticket', id => $nr) };
157         warn "# ticket $nr ",dump($ticket);
158
159         next unless $ticket;
160
161         $ticket->{zotero_items} = $ticket_items->{$nr};
162
163         my $modified = $db->modify( "rt/$nr" => sub {
164                 my $doc = shift;
165                 $doc->{$_} = $ticket->{$_} foreach keys %$ticket;
166                 return $doc;
167         });
168
169         warn "# modified ",dump($modified);
170
171         # copy attachments to CouchDB (they never change, so do it just once
172         if ( my @attachment_ids = $rt->get_attachment_ids( id => $nr ) ) {
173
174                 warn "# get_attachment_ids = ",dump( @attachment_ids );
175                 my $doc = $db->get("rt/$nr");
176                 my @attachments;
177
178                 foreach my $attachment_id ( @attachment_ids ) {
179                         my $attachment = $rt->get_attachment( parent_id => $nr, id => $attachment_id );
180                         if ( $attachment->{Filename} && $attachment->{ContentEncoding} eq 'base64' ) {
181                                 #$attachment->{Filename} ||= $attachment_id;
182                                 my $content = delete $attachment->{Content};
183                                 if ( ! exists $doc->{_attachments}->{ $attachment->{Filename} } ) {
184                                         utf8::encode($content) || warn "utf8::encode error!";
185                                         warn "# extracted ",length( $content ), " bytes";
186                                         warn "## attachment ",dump( $attachment );
187                                         my $url = sprintf 'rt/%d/%s?rev=%s', $nr, uri_escape($attachment->{Filename}), $modified->{rev};
188 #                                       $modified = $db->request( PUT => $url, $content, $attachment->{ContentType} );
189                                 }
190                         }
191                         push @attachments, $attachment;
192                 }
193
194
195                 $db->modify( "rt/$nr" => sub {
196                         my $doc = shift;
197                         $doc->{attachments} = [ @attachments ];
198                         warn "## attachments on $nr = ", $#attachments + 1;
199                         return $doc;
200                 }) if @attachments;
201         
202         }
203
204         if ( $ticket->{Queue} !~ m/ILL/i ) {
205                 warn "SKIP $ticket not in ILL queue!";
206                 next;
207         }
208
209         foreach my $id ( @{ $ticket_items->{$nr} } ) {
210                 warn "# item $id ",dump( $items->{$id} );
211
212 #               $rt->comment( ticket_id => $nr, message => dump( $items->{$id} ) );
213
214         }
215
216 }
217
218 __DATA__
219 {"_id":"_design/zotero","language":"javascript","views":{"itemType":{"map":"function(doc) {\n  emit(doc.zapi.itemType,1);\n}","reduce":"_count"},"updated":{"map":"function(doc) {\n  emit(doc.updated,1);\n}","reduce":"_count"},"tags":{"map":"function(doc) {\n  \n  doc.content.tags.forEach( function(v) {\n    emit(v, doc._id);\n  });\n}","reduce":"_count"},"link_up":{"map":"function(doc) {\n  if ( doc.link[1].rel == 'up' )\n  emit( doc.link[1].key, doc._id );\n}","reduce":"_count"},"year,publisher":{"map":"function(doc) {\n  if ( doc.zapi.year )\n  emit([doc.zapi.year, doc.content.publisher], 1);\n}","reduce":"_count"}}}