Mail/Email/IMAP.pm untested

filter: Statementstmt 0.0% 0 / 130 Branchbran 0.0% 0 / 36 Conditioncond 0.0% 0 / 12 MC/DCmcdc 0.0% 0 / 6 Subroutinesub 0.0% 0 / 26 Podpod 0.0% 0 / 14 totaltotal 0.0% 0 / 224 CC 19 SCAR 40.7
CC
19
Cov
0%
body
182.0
from_imap_client
30.0
subject
6.0
CRAP 58.7
1 package Mail::Email::IMAP;
2 use strict;
3 use MIME::WordDecoder;
4 use MIME::Base64;
5 use MIME::QuotedPrint;
6 use Scalar::Util qw(weaken);
7 use Encode qw(decode);
8 use Text::Markdown ();
9 use HTTP::Date qw( time2isoz );
10 use Time::Piece;
11 #use 5.016; # for fc
12  
13 use Mail::Clean 'clean_subject';
14 use vars qw($VERSION);
15 $VERSION = '0.06';
16  
17 sub new {
18 my $class = shift;
19 bless {
20 text_formatter => Text::Markdown->new(),
21 @_,
22 } => $class;
23 };
24  
25 sub from_imap_client {
26 my ($package, $conn, $uid, %info) = @_;
27 #weaken $conn;
28
29 my $dt = $conn->date( $uid );
30
31 my $timestamp;
32 if( $dt ) {
33 $dt =~ s!\s*\(([A-Z]+.*?)\)\s*$!!; # strip clear name of timezone at end
34 $dt =~ s!\s*$!!; # Strip whitespace at end
35 $dt =~ s!\bUTC$!GMT!; # "UTC" -> "GMT", ah, well...
36
37 # Let's be lenient about the time format:
38 my $format = '%d %b %Y %H:%M:%S';
39
40 if( $dt =~ /,/ ) {
41 # As good citizens, they added the weekday name:
42 $format = "%a, $format";
43  
44 };
45 if( $dt =~ /[A-Z]+$/ ) {
46 # Instead of an offset, we have the name :-/
47 $format = $format . " %Z";
48  
49 } else {
50 # The default, for well-formed servers, an TZ offset
51 $format .= " %z";
52 };
53
54 if( ! eval { $timestamp = Time::Piece->strptime( $dt, $format ); 1 }) {
55 die "$@:\n$format - [$dt]\n";
56 };
57 } else {
58 $dt ||= '';
59 warn "No timestamp for $uid?! [$dt]";
60 };
61
62 my $self = $package->new(
63 %info,
64 uid => $uid,
65 date => $timestamp,
66 imap => $conn,
67 body => $conn->get_bodystructure($uid),
68 envelope => $conn->get_envelope($uid),
69 categories => [],
70 );
71
72 $self
73 };
74  
75 sub imap() {
76 $_[0]->{imap}
77 };
78  
79 # Install our reflectors for the envelope
80 BEGIN {
81 no strict 'refs';
82 for my $acc (qw< inreplyto >) {
83 *{"$acc"} = sub {
84 $_[0]->{envelope}->$acc
85 };
86 };
87
88 };
89  
90 sub subject {
91 if( ! $_[0]->{envelope} ) {
92 warn Dumper $_[0];
93 };
94 my $str = clean_subject( mime_to_perl_string( $_[0]->{ envelope }->subject ) );
95 };
96  
97 sub from {
98 mime_to_perl_string( $_[0]->{ envelope }->from );
99 };
100  
101 sub recipients {
102 map { mime_to_perl_string( $_ ) }
103 grep { defined $_ }
104 ( $_[0]->{ envelope }->from,
105 $_[0]->{ envelope }->cc,
106 $_[0]->{ envelope }->bcc,
107 )
108 };
109  
110 sub uid { $_[0]->{uid} };
111 sub messageid { my $id = $_[0]->{envelope}->{messageid}; $id =~ s!^<(.*)>$!$1!; $id };
112  
113 sub date { $_[0]->{date} };
114 sub year { $_[0]->date->year };
115 sub month { $_[0]->date->strftime('%m') };
116  
117 =head2 C<< ->body( $pref ) >>
118  
119 Finds the preferred body type or one of HTML, PLAIN
120 (in that order)
121  
122 =cut
123  
124 # Check for inline images
125 # Check for other linked media and inline it
126  
127 sub best_alternative {
128 my( $self, $body ) = @_;
129 my $part;
130 ($part)= grep { #warn $_ . " (". $_->bodysubtype . ")";
131 'HTML' eq uc $_->bodysubtype
132 }
133 grep { 'HEAD' ne $_->bodytype }
134 $body->bodystructure;
135 if(! $part) {
136 ($part) = grep { #warn $_ . " (". $_->bodysubtype . ")";
137 'PLAIN' eq $_->bodysubtype
138 }
139 grep { 'HEAD' ne $_->bodytype }
140 $body->bodystructure;
141 };
142 return $part
143 }
144  
145 sub body {
146 my $self = shift;
147
148 # We should query:
149 # If multipart/alternative:
150 # Choose text/html
151 # Choose text/plain
152 # else
153 # use whatever we got
154 # And then look for attached images
155 #warn Dumper [ $self->{body}->parts ];
156 #warn Dumper $self->{body}->bodystructure;
157
158 #warn $self->{body}->bodytype . "/" . $self->{body}->bodysubtype;
159 #for ($self->{body}->parts) {
160 # warn "Part: $_";
161 # warn Dumper $self->{imap}->bodypart_string( $self->{uid}, $_ );
162 #};
163
164 # Recursively enumerate the body parts
165 my %elements= (
166 text => [],
167 images => [],
168 );
169
170 my $body = $self->{body};
171 my @toplevel = grep { $_->id =~ /^\d+$/ } $body->bodystructure;
172
173 if( ! @toplevel ) {
174 @toplevel = $body;
175 };
176
177 for my $part (@toplevel) {
178 # This walks the whole mail structure
179 #warn sprintf "Part %s", $part->id;
180 my $mime= sprintf "%s/%s", lc $part->bodytype, lc $part->bodysubtype;
181 #warn $mime;
182
183 if( 'multipart/alternative' eq $mime ) {
184 # -> subroutine: get_best_alternative()
185 #warn "Have multipart bodytype, finding best alternative";
186 # find suitable part
187 # Assume it's about text anyway
188 # Cascade from HTML -> plaintext
189 $part = $self->best_alternative( $part );
190 push @{ $elements{ text } }, {
191 content => $self->imap()->bodypart_string( $self->{uid}, $part->id ),
192 mime => $mime,
193 part => $part
194 };
195 #warn Dumper $elements{ text }->[-1];
196 } elsif( 'multipart/mixed' eq $mime ) {
197 # Find the different types (image, text, sound?) and use
198 # one from each, resp concatenate
199 # -> subroutine: get_parts()
200
201 } else {
202 #warn sprintf "Have only one body type (%s)", $part->bodytype;
203 # take what we got
204
205 if( 'image' eq $part->bodytype ) {
206 my $ref = $part->bodyparms;
207 next if( ! ref $part->bodyparms );
208 my $name = $part->bodyparms->{name};
209 # Download the image so we can later serve it up again under its name
210 #push @{ $elements{ images } }, $part->textlines;
211 #$body = sprintf '<img src="/%s/%s">',
212 # $self->permabase,
213 # $name;
214 #warn "Image detected, serving up as '$body'";
215 @{ $elements{ text } } = { content => $body, mime => "text/html", part => undef };
216
217 } elsif( 'text/plain' eq $mime ) {
218 push @{ $elements{ text } }, {
219 content => $self->imap()->bodypart_string( $self->{uid}, $part->id ),
220 mime => $mime,
221 part => $part
222 };
223  
224 # we should handle text/html more gracefully!
225 } else {
226 #my $body= $part->textlines;
227 #warn "Unknown / unhandled part $mime, hope it's text.";
228
229 #warn Dumper $part;
230 push @{ $elements{ text } }, {
231 content => $self->imap()->bodypart_string( $self->{uid}, $part->id ),
232 mime => $mime,
233 part => $part
234 };
235 };
236 };
237 };
238
239 if( ! @{$elements{ text }}) {
240 return 'No mail body';
241 };
242  
243 $body= $elements{ text }->[0]->{content};
244 my $type= $elements{ text }->[0]->{mime};
245 my $part= $elements{ text }->[0]->{part};
246
247 # Decode the transport encoding
248 if( $part and 'base64' eq $part->bodyenc ) {
249 $body = decode_base64( $body );
250 } elsif( $part and 'quoted-printable' eq $part->bodyenc ) {
251 $body = decode_qp( $body );
252 };
253
254 # Decode to appropriate charset
255 if( $part and ref $part and my $enc = $part->bodyparms->{charset}) {
256 $body = decode( $enc, $body );
257 };
258
259 # Find out whether we have HTML or plaintext
260 if( 'text/plain' eq $type ) {
261 $part= $body;
262  
263 # Maybe this should go into a separate sub/module
264 # Strip mail footer
265 $body=~ s!\n--\s*\n.*!!sm;
266
267 # Strip obvious reply:
268 $body=~ s!----- Reply message -----.*!!sm;
269
270 # Strip quoted part in case we have a reply
271 # A reply counts as
272 # a line ending with ":" as the "$foo wrote on $date:"
273 # followed by more than three (consecutive!) quoted lines
274 $body=~ s!^[A-Z].*:(?:\s*^>.*$){3,}!!mg;
275 #or warn "No quoted part found";
276  
277 # Fix the hardcoded ->markdown method
278 # Maybe this should go into a separate sub/module
279 $body= $self->{text_formatter}->markdown( $body );
280 } elsif( 'text/html' eq $type ) {
281  
282 # Strip JS and other stuff, resp. only allow good stuff
283 # Most likely Clinton's HTML::StripScripts is the module to use
284 # Maybe this should go into a separate sub/module
285 # Also, we should use an HTML parser
286
287 $body=~ s!<br>\s*--\s*<br>.*!!ms; # Strip mail footer
288 };
289
290 $body
291 };
292  
293 1;