blib/lib/HTTP/Promise/Entity.pm untested

filter: Statementstmt 0.0% 0 / 997 Branchbran 0.0% 0 / 610 Conditioncond 0.0% 0 / 514 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 75 Podpod 0.0% 0 / 60 totaltotal 0.0% 0 / 2256 CC 306 SCAR 61.8
CC
306
Cov
0%
build
1406.0
content_charset
1190.0
decode_body
1056.0
CRAP 480.6
1 ##----------------------------------------------------------------------------
2 ## Asynchronous HTTP Request and Promise - ~/lib/HTTP/Promise/Entity.pm
3 ## Version v0.2.2
4 ## Copyright(c) 2023 DEGUEST Pte. Ltd.
5 ## Author: Jacques Deguest <jack@deguest.jp>
6 ## Created 2022/04/19
7 ## Modified 2025/08/30
8 ## All rights reserved.
9 ##
10 ##
11 ## This program is free software; you can redistribute it and/or modify it
12 ## under the same terms as Perl itself.
13 ##----------------------------------------------------------------------------
14 package HTTP::Promise::Entity;
15 BEGIN
16 {
17 use strict;
18 use warnings;
19 warnings::register_categories( 'HTTP::Promise' );
20 use parent qw( Module::Generic );
21 use vars qw( $VERSION $EXCEPTION_CLASS $BOUNDARY_DELIMITER $BOM2ENC $ENC2BOM $BOM_RE
22 $BOM_MAX_LENGTH $DEFAULT_MIME_TYPE );
23 use Data::UUID;
24 use HTTP::Promise::Exception;
25 use HTTP::Promise::Headers;
26 use HTTP::Promise::Body;
27 use Module::Generic::HeaderValue;
28 # use Nice::Try;
29 use Symbol;
30 use URI::Escape::XS ();
31 use constant CRLF => "\015\012";
32 our $EXCEPTION_CLASS = 'HTTP::Promise::Exception';
33 our $BOUNDARY_DELIMITER = "\015\012";
34 our $DEFAULT_MIME_TYPE = 'application/octet-stream';
35 our $VERSION = 'v0.2.2';
36 };
37  
38 use strict;
39 use warnings;
40  
41 sub init
42 {
43 my $self = shift( @_ );
44 $self->{body} = undef;
45 # Sie minimum from which compression is enabled, if mime type is suitable.
46 # Defaults to 200Kb
47 $self->{compression_min}= 204800;
48 $self->{effective_type} = undef;
49 $self->{epilogue} = undef;
50 $self->{ext_vary} = undef;
51 $self->{headers} = undef;
52 $self->{is_encoded} = 0;
53 $self->{output_dir} = undef;
54 $self->{preamble} = undef;
55 $self->{_init_strict_use_sub} = 1;
56 $self->{_exception_class} = $EXCEPTION_CLASS;
57 $self->SUPER::init( @_ ) || return( $self->pass_error );
58 $self->{_parts} = [];
59 return( $self );
60 }
61  
62 sub add_part
63 {
64 my $self = shift( @_ );
65 my( $part, $index ) = @_;
66 return( $self->error( "Part provided is not a HTTP::Promise::Entity object." ) ) if( !$self->_is_a( $part => 'HTTP::Promise::Entity' ) );
67 my $parts = $self->_parts;
68 $index = -1 if( !defined( $index ) );
69 $index = $parts->size + 2 + $index if( $index < 0 );
70 $parts->splice( $index, 0, $part );
71 return( $part );
72 }
73  
74 sub as_form_data
75 {
76 my $self = shift( @_ );
77 my $type = $self->headers->type;
78 return(0) unless( lc( $type ) eq 'multipart/form-data' );
79 $self->_load_class( 'HTTP::Promise::Body::Form::Data' ) || return( $self->pass_error );
80 my $form = HTTP::Promise::Body::Form::Data->new;
81 $form->debug( $self->debug // 0 );
82 my $parts = $self->parts;
83 # nothing to do
84 return( $form ) if( $parts->is_empty );
85 foreach my $part ( @$parts )
86 {
87 my $headers = $part->headers;
88 my $body = $part->body;
89 my $name;
90 my $dispo = $headers->content_disposition;
91 next unless( $dispo );
92 my $cd = $headers->new_field( 'Content-Disposition' => "$dispo" );
93 return( $self->pass_error( $headers->error ) ) if( !defined( $cd ) );
94 $name = $cd->name;
95 next if( !defined( $name ) || !length( "$name" ) );
96 my $encodings = $headers->content_encoding;
97 if( $part->is_encoded && $encodings )
98 {
99 $body = $part->decode_body( encoding => $encodings ) ||
100 return( $self->pass_error( $part->error ) );
101 }
102
103 my $field = $form->new_field(
104 name => $name,
105 body => $body,
106 headers => $headers,
107 );
108 return( $self->pass_error( $form->error ) ) if( !defined( $field ) );
109
110 if( exists( $form->{ $name } ) )
111 {
112 $form->{ $name } = [$form->{ $name }];
113 push( @{$form->{ $name }}, $field );
114 }
115 else
116 {
117 $form->{ $name } = $field;
118 }
119 }
120 return( $form );
121 }
122  
123 sub as_string
124 {
125 my $self = shift( @_ );
126 my $eol = shift( @_ );
127 my $opts = $self->_get_args_as_hash( @_ );
128 $opts->{eol} = $eol if( defined( $eol ) );
129 my $output = $self->new_scalar;
130 # Because of an edge case where open with :binmode(utf-8) layer does not decode properly \x{FF}
131 # but Encode::decode( 'utf-8', $buff ) does, and since the body is loaded into a string
132 # anyway, we first read the data as raw and then decode it with Encode
133 my $binmode;
134 if( exists( $opts->{binmode} ) &&
135 length( $opts->{binmode} ) &&
136 lc( substr( $opts->{binmode}, 0, 3 ) ) eq 'utf' )
137 {
138 $binmode = delete( $opts->{binmode} );
139 $opts->{binmode} = 'raw';
140 }
141 my $fh = $output->open( '>' ) || return( $self->pass_error( $output->error ) );
142 $fh->binmode( ':raw' );
143 # $self->print( $fh, ( scalar( keys( %$opts ) ) ? $opts : () ) ) || return( $self->pass_error );
144 $self->print( $fh, ( scalar( keys( %$opts ) ) ? $opts : () ) ) || return( $self->pass_error );
145 $fh->close;
146 if( defined( $binmode ) )
147 {
148 $self->_load_class( 'Encode' ) || return( $self->pass_error );
149 # try-catch
150 local $@;
151 eval
152 {
153 $$output = Encode::decode( $binmode, $$output, ( Encode::FB_DEFAULT | Encode::LEAVE_SRC ) );
154 };
155 if( $@ )
156 {
157 return( $self->error( "Error decoding body content with character encoding '$binmode': $@" ) );
158 }
159 }
160 return( $output );
161 }
162  
163 sub attach
164 {
165 my $self = shift( @_ );
166 my $class = ref( $self ) || $self;
167 $self->make_multipart || return( $self->pass_error );
168 my $part = $class->build( @_, top => 0 ) ||
169 return( $self->pass_error( $class->error ) );
170 return( $self->add_part( $part ) );
171 }
172  
173 sub body { return( shift->_set_get_object_without_init( 'body', [qw( HTTP::Promise::Body HTTP::Promise::Body::Form )], @_ ) ); }
174  
175 sub body_as_array
176 {
177 my $self = shift( @_ );
178 my $eol = @_ ? shift( @_ ) : CRLF;
179 return( $self->error( "You cannot use the method body() to set the encoded contents." ) ) if( scalar( @_ ) );
180 my $output = $self->new_scalar;
181 my $fh = $output->open( '>' ) ||
182 return( $self->pass_error( $output->error ) );
183 $self->print_body( $fh ) || return( $self->pass_error );
184 $fh->close;
185 my $ary = $output->split( qr/\015?\012/ );
186 for( @$ary )
187 {
188 $_ .= $eol;
189 }
190 return( $ary );
191 }
192  
193 sub body_as_string
194 {
195 my $self = shift( @_ );
196 my $opts = $self->_get_args_as_hash( @_ );
197 my $output = $self->new_scalar;
198 # Because of an edge case where open with :binmode(utf-8) layer does not decode properly \x{FF}
199 # but Encode::decode( 'utf-8', $buff ) does, and since the body is loaded into a string
200 # anyway, we first read the data as raw and then decode it with Encode
201 my $binmode;
202 if( exists( $opts->{binmode} ) &&
203 length( $opts->{binmode} ) &&
204 lc( substr( $opts->{binmode}, 0, 3 ) ) eq 'utf' )
205 {
206 $binmode = delete( $opts->{binmode} );
207 $opts->{binmode} = 'raw';
208 }
209 my $fh = $output->open( '>' ) ||
210 return( $self->pass_error( $output->error ) );
211 $self->print_body( $fh, ( scalar( keys( %$opts ) ) ? $opts : () ) ) || return( $self->pass_error );
212 $fh->close;
213 if( defined( $binmode ) )
214 {
215 $self->_load_class( 'Encode' ) || return( $self->pass_error );
216 # try-catch
217 local $@;
218 eval
219 {
220 $$output = Encode::decode( $binmode, $$output, ( Encode::FB_DEFAULT | Encode::LEAVE_SRC ) );
221 };
222 if( $@ )
223 {
224 return( $self->error( "Error decoding body content with character encoding '$binmode': $@" ) );
225 }
226 }
227 return( $output );
228 }
229  
230 sub build
231 {
232 my $self = shift( @_ );
233 my( $opts, $order ) = $self->_get_args_as_hash( @_ );
234 my( $field, $filename, $boundary );
235 my $type = delete( $opts->{type} ) || 'text/plain';
236 my $charset = delete( $opts->{charset} );
237 my $is_multipart = ( $type =~ m{^multipart/}i ? 1 : 0 );
238 my $encoding = delete( $opts->{encoding} ) || '';
239 my $desc = delete( $opts->{description} );
240 my $top = exists( $opts->{top} ) ? delete( $opts->{top} ) : 1;
241 # my $disposition = $opts->{disposition} || 'inline';
242 # inline, attachment or multipart/form-data
243 # Ref: <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition>
244 # We could, technically, default to 'inline' and end up with something like:
245 # Content-Disposition: inline; filename=foo.txt
246 # But, even though it would be ok for mail, for HTTP, it would be weird, so, no default
247 # and instead if a path is provided, but no Content-Disposition, we fall back to 'attachment'
248 my $disposition = delete( $opts->{disposition} );
249 my $id = delete( $opts->{id} );
250 my $debug = delete( $opts->{debug} ) // 0;
251 # Ensure this is an object
252 my $new = $self->new( debug => $debug ) || return( $self->pass_error );
253 my $headers = HTTP::Promise::Headers->new( { debug => $self->debug } ) ||
254 return( $self->pass_error( HTTP::Promise::Headers->error ) );
255 $new->headers( $headers );
256
257 # Either data or path
258 my $data = delete( $opts->{data} );
259 my $path = delete( $opts->{path} );
260 my( $path_fname ) = ( ( $path || '' ) =~ m{([^/]+)\Z} );
261 $filename = ( exists( $opts->{filename} ) ? delete( $opts->{filename} ) : $path_fname );
262 $filename = undef() if( defined( $filename ) and $filename eq '' );
263 my $filename_utf8;
264 if( defined( $filename ) && length( $filename ) && $filename =~ /[^\w\.]+/ )
265 {
266 $filename_utf8 = $new->headers->encode_filename( $filename );
267 }
268 if( defined( $encoding ) &&
269 $type =~ m{^(multipart/|message/(rfc822|partial|external-body|delivery-status|disposition-notification|feedback-report|http)$)}i )
270 {
271 undef( $encoding );
272 }
273
274 # Multipart or not? Do sanity check and fixup:
275 if( $is_multipart )
276 {
277 # Get any supplied boundary, and check it:
278 if( defined( $boundary = delete( $opts->{boundary} ) ) )
279 {
280 if( !length( $boundary ) )
281 {
282 warn( "Empty string not a legal boundary: I am ignoring it\n" ) if( $self->_warnings_is_enabled );
283 $boundary = undef();
284 }
285 elsif( $boundary =~ m{[^0-9a-zA-Z_\'\(\)\+\,\.\/\:\=\?\- ]} )
286 {
287 warn( "Boundary ignored: illegal characters ($boundary)\n" ) if( $self->_warnings_is_enabled );
288 $boundary = undef();
289 }
290 }
291 # If we have to roll our own boundary, do so:
292 $boundary = $new->make_boundary if( !defined( $boundary ) );
293 }
294 # Or this is a single part
295 else
296 {
297 # Create body:
298 if( defined( $path ) && length( $path ) )
299 {
300 my $f = HTTP::Promise::Body::File->new( $path ) ||
301 return( $self->pass_error( HTTP::Promise::Body::File->error ) );
302 $new->body( $f ) || return( $self->pass_error );
303 # Set the Content-Disposition to 'attachment' by default if not set
304 # $disposition = 'attachment' if( !defined( $disposition ) || !length( $disposition ) );
305 }
306 elsif( defined( $data ) && length( $data ) )
307 {
308 my $s = HTTP::Promise::Body::InCore->new( $data ) ||
309 return( $self->pass_error( HTTP::Promise::Body::InCore->error ) );
310 $new->body( $s ) || return( $self->pass_error );
311 }
312 else
313 {
314 return( $self->error( "Unable to build HTTP entity: no body, and not multipart" ) );
315 }
316 # $self->body->binmode(1) unless( $self->textual_type( $type ) );
317 }
318
319 my $ct = Module::Generic::HeaderValue->new_from_header( $type );
320 return( $self->pass_error( Module::Generic::HeaderValue->error ) ) if( !defined( $ct ) );
321 $ct->param( charset => $charset ) if( $charset );
322 if( defined( $filename_utf8 ) )
323 {
324 $ct->param( 'name*' => sprintf( "UTF-8''%s", $filename_utf8 ) );
325 }
326 elsif( defined( $filename ) )
327 {
328 $ct->param( name => $filename );
329 }
330 $ct->param( boundary => $boundary ) if( defined( $boundary ) );
331 $headers->replace( 'Content-Type' => "$ct" );
332
333 if( defined( $encoding ) && lc( $encoding ) eq 'suggest' )
334 {
335 $encoding = $new->suggest_encoding;
336 }
337
338 # unless( $is_multipart )
339 if( !$is_multipart && ( defined( $disposition ) || defined( $filename ) ) )
340 {
341 $disposition = 'attachment' if( !defined( $disposition ) );
342 $field = Module::Generic::HeaderValue->new_from_header( ( defined( $disposition ) ? $disposition : () ) );
343 return( $self->pass_error( Module::Generic::HeaderValue->error ) ) if( !defined( $field ) );
344 if( defined( $filename_utf8 ) )
345 {
346 $field->param( 'filename*' => sprintf( "UTF-8''%s", $filename_utf8 ) );
347 }
348 elsif( defined( $filename ) )
349 {
350 $field->param( filename => $filename );
351 }
352 $headers->replace( 'Content-disposition', "$field" );
353 }
354 $headers->replace( 'Content-encoding', $encoding ) if( defined( $encoding ) && length( $encoding ) );
355 if( defined( $desc ) && length( $desc ) )
356 {
357 warn( "There is no Content-Description in HTTP protocole\n" ) if( $self->_warnings_is_enabled );
358 }
359  
360 if( defined( $id ) )
361 {
362 warn( "There is no Content-ID for HTTP multipart data\n" ) if( $self->_warnings_is_enabled );
363 }
364
365 foreach( @$order )
366 {
367 # Maybe it has been removed since then? So that only headers remain
368 next if( !exists( $opts->{ $_ } ) );
369 # Value is undef -> remove the header, if any.
370 if( !defined( $opts->{ $_ } ) )
371 {
372 $headers->remove_header( $_ );
373 }
374 elsif( length( $opts->{ $_ } ) )
375 {
376 $headers->delete( $_ );
377 foreach my $val ( $self->_is_array( $opts->{ $_ } ) ? @{$opts->{ $_ }} : ( $opts->{ $_ } ) )
378 {
379 $headers->add( $_ => $val );
380 }
381 }
382 }
383 return( $new );
384 }
385  
386 sub clone
387 {
388 my $self = shift( @_ );
389 my $opts = $self->_get_args_as_hash( @_ );
390 $opts->{clone_message} //= 1;
391 my $addr = $self->_refaddr( $self );
392 my $new = $self->new;
393 my( $new_headers, $new_body, $new_parts );
394 my $headers = $self->headers;
395 my $body = $self->body;
396 $new_headers = $headers->clone if( defined( $headers ) );
397 $new_body = $body->clone if( defined( $body ) );
398 my $parts = $self->parts;
399 if( !$parts->is_empty )
400 {
401 $new_parts = $self->new_array;
402 # Each part is an HTTP::Promise::Entity
403 for( @$parts )
404 {
405 my $paddr = $self->_refaddr( $_ );
406 # This would be weird, but let's do it anyway
407 if( $paddr eq $addr )
408 {
409 $new_parts->push( $new );
410 next;
411 }
412 my $new_part = $_->clone;
413 $new_parts->push( $new_part );
414 }
415 $new->parts( $new_parts );
416 }
417 $new->headers( $new_headers ) if( defined( $new_headers ) );
418 $new->body( $new_body ) if( defined( $new_body ) );
419 $new->name( $self->name ) if( $self->name );
420 $new->is_encoded( $self->is_encoded );
421 $new->debug( $self->debug );
422 $new->preamble( $self->preamble->clone );
423 $new->epilogue( $self->epilogue->clone );
424 $new->compression_min( $self->compression_min );
425 $new->effective_type( $self->effective_type );
426 my $msg;
427 if( ( $msg = $self->http_message ) && $opts->{clone_message} )
428 {
429 # To prevent endless recursion
430 my $new_msg = $msg->clone( clone_entity => 0 );
431 $new_msg->headers( $new_headers );
432 $new_msg->entity( $new );
433 $new->http_message( $new_msg );
434 }
435 return( $new );
436 }
437  
438 sub compression_min { return( shift->_set_get_number( 'compression_min', @_ ) ); }
439  
440 # NOTE: an outdated method since nowadays everyone use UTF-8
441 # This is not intended to be a generic method, but instead to be used specifically for this entity
442 # content parameter can be provided to avoid reading from the body if we already have data handy.
443 sub content_charset
444 {
445 my $self = shift( @_ );
446 my $opts = $self->_get_args_as_hash( @_ );
447 my $headers = $self->headers;
448 # If parameter content_type_charset is set to false, this means it was just tried and
449 # we should not try it again.
450 if( ( my $charset = $headers->content_type_charset ) &&
451 ( !exists( $opts->{content_type_charset} ) || $opts->{content_type_charset} ) )
452 {
453 return( $charset );
454 }
455  
456 $self->_load_class( 'Encode' ) || return( $self->pass_error );
457 unless( defined( $BOM2ENC ) && scalar( %$BOM2ENC ) )
458 {
459 # Credits: Matthew Lawrence (File::BOM)
460 our $BOM2ENC = +{
461 map{ Encode::encode( $_, "\x{feff}" ) => $_ } qw(
462 UTF-8
463 UTF-16BE
464 UTF-16LE
465 UTF-32BE
466 UTF-32LE
467 )
468 };
469  
470 our $ENC2BOM = +{
471 reverse( %$BOM2ENC ),
472 map{ $_ => Encode::encode( $_, "\x{feff}" ) } qw(
473 UCS-2
474 iso-10646-1
475 utf8
476 )
477 };
478 my @boms = sort{ length( $b ) <=> length( $a ) } keys( %$BOM2ENC );
479 our $BOM_MAX_LENGTH = length( $boms[0] );
480 {
481 local $" = '|';
482 our $BOM_RE = qr/@boms/;
483 }
484 }
485
486 # time to start guessing
487 # If called from decoded_content, kind of pointless to call decoded_content again
488 my $cref;
489 if( exists( $opts->{content} ) && length( $opts->{content} ) )
490 {
491 return( $self->error( "Unsupported data type (", ref( $opts->{content} ), ")." ) ) if( ref( $opts->{content} ) && !$self->_is_scalar( $opts->{content} ) );
492 $cref = $self->_is_scalar( $opts->{content} ) ? $opts->{content} : \$opts->{content};
493 }
494 else
495 {
496 my $body = $self->body || return( '' );
497 my $io = $body->open( '<', { binmode => 'raw' } ) ||
498 return( $self->pass_error( $body->error ) );
499 my $buff;
500 my $bytes = $io->read( $buff, 4096 );
501 return( $self->pass_error( $io->error ) ) if( !defined( $bytes ) );
502 return( '' ) if( !$bytes );
503 $cref = \$buff;
504 }
505
506 # Is there a Byte Order Mark?
507 if( $$cref =~ /^($BOM_RE)/ )
508 {
509 my $bom = $1;
510 return( $BOM2ENC->{ $bom } );
511 }
512  
513 # Unicode BOM
514 return( 'UTF-8' ) if( $$cref =~ /^\xEF\xBB\xBF/ );
515 return( 'UTF-32LE' ) if( $$cref =~ /^\xFF\xFE\x00\x00/ );
516 return( 'UTF-32BE' ) if( $$cref =~ /^\x00\x00\xFE\xFF/ );
517 return( 'UTF-16LE' ) if( $$cref =~ /^\xFF\xFE/ );
518 return( 'UTF-16BE' ) if( $$cref =~ /^\xFE\xFF/ );
519  
520 if( $headers->content_is_xml )
521 {
522 # http://www.w3.org/TR/2006/REC-xml-20060816/#sec-guessing
523 # XML entity not accompanied by external encoding information and not
524 # in UTF-8 or UTF-16 encoding must begin with an XML encoding declaration,
525 # in which the first characters must be '<?xml'
526 return( 'UTF-32BE' ) if( $$cref =~ /^\x00\x00\x00</ );
527 return( 'UTF-32LE' ) if( $$cref =~ /^<\x00\x00\x00/ );
528 return( 'UTF-16BE' ) if( $$cref =~ /^(?:\x00\s)*\x00</ );
529 return( 'UTF-16LE' ) if( $$cref =~ /^(?:\s\x00)*<\x00/ );
530 if( $$cref =~ /^[[:blank:]\h]*(<\?xml[^\x00]*?\?>)/ )
531 {
532 if( $1 =~ /[[:blank:]\h\v]encoding[[:blank:]\h\v]*=[[:blank:]\h\v]*(["'])(.*?)\1/ )
533 {
534 my $enc = $2;
535 $enc =~ s/^[[:blank:]\h]+//;
536 $enc =~ s/[[:blank:]\h]+\z//;
537 return( $enc ) if( $enc );
538 }
539 }
540 return( 'UTF-8' );
541 }
542 elsif( $headers->content_is_text )
543 {
544 my $encoding = $self->guess_character_encoding( content => $cref, object => 1 );
545 return( ref( $encoding ) ? $encoding->mime_name : $encoding ) if( $encoding );
546 }
547 elsif( $headers->content_type eq 'application/json' )
548 {
549 # RFC 4627, ch 3
550 return( 'UTF-32BE' ) if( $$cref =~ /^\x00\x00\x00./s );
551 return( 'UTF-32LE' ) if( $$cref =~ /^.\x00\x00\x00/s );
552 return( 'UTF-16BE' ) if( $$cref =~ /^\x00.\x00./s );
553 return( 'UTF-16LE' ) if( $$cref =~ /^.\x00.\x00/s );
554 return( 'UTF-8' );
555 }
556 # if( $headers->content_type =~ /^text\// && $self->_load_class( 'Encode' ) )
557 if( $headers->content_type =~ /^text\// )
558 {
559 if( length( $$cref ) )
560 {
561 return( 'US-ASCII' ) unless( $$cref =~ /[\x80-\xFF]/ );
562 my $encoding;
563 # try-catch
564 local $@;
565 eval
566 {
567 Encode::decode_utf8( $$cref, ( Encode::FB_CROAK | Encode::LEAVE_SRC ) );
568 $encoding = 'UTF-8';
569 };
570 if( $@ )
571 {
572 return( $self->error( "Failed to decode utf8 content: $@" ) );
573 }
574 # return( 'ISO-8859-1' );
575 return( $encoding );
576 }
577 }
578 return( '' );
579 }
580  
581 sub decode_body
582 {
583 my $self = shift( @_ );
584 my $this = shift( @_ );
585 my $opts = $self->_get_args_as_hash( @_ );
586 return( $self->error( "No decoding string or array has been provided." ) ) if( !defined( $this ) );
587 return( $self->error( "Bad argument provided. decode_body() accepts only either an array of encodings or a string or something that stringifies." ) ) if( !$self->_is_array( $this ) && ( ref( $this ) && !overload::Method( $this => '""' ) ) );
588 my $encodings = $self->_is_array( $this ) ? $this : [split( /[[:blank:]\h]*,[[:blank:]\h]*/, "${this}" )];
589 $opts->{replace} //= 1;
590 $opts->{raise_error} //= 0;
591 $self->_load_class( 'HTTP::Promise::Stream' ) || return( $self->error );
592 my $body = $self->body;
593 warn( "No encoding were provided to decode the HTTP body.\n" ) if( !scalar( @$encodings ) && warnings::enabled( 'HTTP::Promise' ) );
594 # Nothing to do
595 return( $self ) if( !$body || !scalar( @$encodings ) );
596 # Parameters to be passed. Transparent set to 0 allow for failure
597 my $enc2params =
598 {
599 bzip2 => { Transparent => 0 },
600 deflate => { Transparent => 0 },
601 inflate => { Transparent => 0 },
602 gzip => { Transparent => 0 },
603 lzf => { Transparent => 0 },
604 lzip => { Transparent => 0 },
605 lzma => { Transparent => 0 },
606 lzop => { Transparent => 0 },
607 rawdeflate => { Transparent => 0 },
608 rawinflate => { Transparent => 0 },
609 xz => { Transparent => 0 },
610 zstd => { Transparent => 0 },
611 };
612
613 if( $body->isa( 'HTTP::Promise::Body::File' ) )
614 {
615 my $f = $body;
616 if( $f->is_empty )
617 {
618 warn( "HTTP Body file '$f' is empty, so there is nothing to decode\n" ) if( warnings::enabled( 'HTTP::Promise' ) );
619 return( $self );
620 }
621 my $ext = $f->extension;
622 my $ext_vary = $self->ext_vary;
623 my $ext_parts;
624 if( $ext_vary )
625 {
626 $ext_parts = $f->extensions;
627 }
628
629 foreach my $enc ( @$encodings )
630 {
631 next if( $enc eq 'identity' || $enc eq 'none' );
632 my $params = {};
633 $params = $enc2params->{ $enc } if( exists( $enc2params->{ $enc } ) );
634 my $s = HTTP::Promise::Stream->new( $f,
635 decoding => $enc,
636 fatal => $opts->{raise_error},
637 debug => $self->debug,
638 ) || return( $self->pass_error( HTTP::Promise::Stream->error ) );
639 my $ext_deb = $s->encoding2suffix( $enc )->first;
640 my $ext_enc;
641 if( $ext_vary &&
642 ( $ext_enc = $s->encoding2suffix( $enc )->first ) &&
643 $ext_parts->[-1] eq $ext_enc )
644 {
645 pop( @$ext_parts );
646 $ext = join( '.', @$ext_parts );
647 }
648 my $tempfile = $self->new_tempfile( extension => $ext );
649 # my $len = $s->read( $tempfile, ( exists( $params->{ $enc } ) ? %{$params->{ $enc }} : () ) );
650 my $len = $s->read( $tempfile, $params );
651 if( !defined( $len ) )
652 {
653 if( $enc eq 'deflate' || $enc eq 'inflate' )
654 {
655 # Try again, but using rawinflate this time
656 if( $s->error->message =~ /Header Error: CRC mismatch/ )
657 {
658 $enc = "raw${enc}";
659 $params = {};
660 $params = $enc2params->{ $enc } if( exists( $enc2params->{ $enc } ) );
661 my $s = HTTP::Promise::Stream->new( $f,
662 decoding => $enc,
663 fatal => $opts->{raise_error}
664 ) || return( $self->pass_error( HTTP::Promise::Stream->error ) );
665 # $len = $s->read( $tempfile, ( exists( $params->{ $enc } ) ? ( $params->{ $enc } ) : () ) );
666 $len = $s->read( $tempfile, $params );
667 return( $self->pass_error( $s->error ) ) if( !defined( $len ) );
668 }
669 else
670 {
671 return( $self->pass_error( $s->error ) )
672 }
673 }
674 else
675 {
676 return( $self->pass_error( $s->error ) );
677 }
678 }
679 return( $self->error( "The decoding pass on the HTTP body file source '$f' to target '$tempfile' with encoding '$enc' resulted in 0 byte decoded!" ) ) if( !$len );
680 $f = $tempfile;
681 }
682 $body = HTTP::Promise::Body::File->new( $f ) ||
683 return( $self->pass_error( HTTP::Promise::Body::File->error ) );
684 if( $opts->{replace} )
685 {
686 $self->body( $body );
687 $self->is_decoded(1);
688 }
689 }
690 elsif( $body->isa( 'HTTP::Promise::Body::Scalar' ) )
691 {
692 my $temp = $body;
693 if( $body->is_empty )
694 {
695 warn( "HTTP Body in memory is empty, so there is nothing to decode\n" ) if( warnings::enabled( 'HTTP::Promise' ) );
696 return( $self );
697 }
698
699 foreach my $enc ( @$encodings )
700 {
701 next if( $enc eq 'identity' || $enc eq 'none' );
702 my $params = {};
703 $params = $enc2params->{ $enc } if( exists( $enc2params->{ $enc } ) );
704 my $s = HTTP::Promise::Stream->new( $temp,
705 decoding => $enc,
706 fatal => $opts->{raise_error},
707 debug => $self->debug
708 ) || return( $self->pass_error( HTTP::Promise::Stream->error ) );
709 my $decoded = $self->new_scalar;
710 # my $len = $s->read( $decoded, ( exists( $params->{ $enc } ) ? ( $params->{ $enc } ) : () ) );
711 my $len = $s->read( $decoded, $params );
712 # my $len = $s->read( $decoded );
713 # return( $self->pass_error( $s->error ) ) if( !defined( $len ) );
714 if( !defined( $len ) )
715 {
716 if( $enc eq 'deflate' || $enc eq 'inflate' )
717 {
718 # Try again, but using rawinflate this time
719 if( $s->error->message =~ /Header Error: CRC mismatch/ )
720 {
721 $enc = "raw${enc}";
722 $params = {};
723 $params = $enc2params->{ $enc } if( exists( $enc2params->{ $enc } ) );
724 my $s = HTTP::Promise::Stream->new( $temp,
725 decoding => $enc,
726 fatal => $opts->{raise_error},
727 debug => $self->debug
728 ) || return( $self->pass_error( HTTP::Promise::Stream->error ) );
729 # $len = $s->read( $decoded, ( exists( $params->{ $enc } ) ? $params->{ $enc } : () ) );
730 $len = $s->read( $decoded, $params );
731 return( $self->pass_error( $s->error ) ) if( !defined( $len ) );
732 }
733 else
734 {
735 return( $self->pass_error( $s->error ) )
736 }
737 }
738 else
739 {
740 return( $self->pass_error( $s->error ) );
741 }
742 }
743 return( $self->error( "The decoding pass on the HTTP body in memory with encoding '$enc' resulted in 0 byte decoded!" ) ) if( !$len );
744 $temp = $decoded;
745 }
746 # Replace content (default)
747 if( $opts->{replace} )
748 {
749 $body->set( $temp );
750 $self->body( $body );
751 $self->is_decoded(1);
752 }
753 # Make a copy to return it
754 else
755 {
756 $body = $body->new( $temp );
757 }
758 }
759 else
760 {
761 return( $self->error( "I do not know how to handle HTTP body object of class ", ref( $body ) ) );
762 }
763 return( $body );
764 }
765  
766 sub dump
767 {
768 my $self = shift( @_ );
769 my $opts = $self->_get_args_as_hash( @_ );
770 my $content = '';
771 my $maxlen = $opts->{maxlength};
772 $maxlen = 512 unless( defined( $maxlen ) );
773 my $no_content = $opts->{no_content};
774 $no_content = "(no content)" unless( defined( $no_content ) );
775 my $body = $self->body;
776 my $chopped = 0;
777 my $mime_type = $self->mime_type;
778 my $toptype;
779 $toptype = [split( '/', lc( $mime_type ), 2 )]->[0] if( defined( $mime_type ) );
780 my $crlf = $HTTP::Promise::Entity::BOUNDARY_DELIMITER || CRLF;
781  
782 if( defined( $body ) )
783 {
784 my $io = $body->open( '<', { binmode => 'raw' } ) ||
785 return( $self->pass_error( $body->error ) );
786 my $bytes = $io->read( $content, ( $maxlen || $body->length ) );
787 return( $self->pass_error( $io->error ) ) if( !defined( $bytes ) );
788 $io->close;
789 my $encoding = $self->headers->mime_encoding;
790 my $encodings = [];
791 $encodings = [split( /[[:blank:]\h]*,[[:blank:]\h]*/, $encoding )] if( defined( $encoding ) && length( $encoding ) );
792 $self->_load_class( 'HTTP::Promise::Stream' ) || return( $self->error );
793 # Process encoding
794 if( scalar( @$encodings ) && !$self->is_encoded )
795 {
796 my $temp = $content;
797 my $has_error = 0;
798 foreach my $enc ( @$encodings )
799 {
800 my $s = HTTP::Promise::Stream->new( $temp, encoding => $enc ) ||
801 return( $self->pass_error( HTTP::Promise::Stream->error ) );
802 my $encoded = $self->new_scalar;
803 my $len = $s->read( $encoded );
804 return( $self->pass_error( $s->error ) ) if( !defined( $len ) );
805 if( !$len )
806 {
807 warn( "The encoding pass on the HTTP body in memory with encoding '$enc' resulted in 0 byte encoded!\n" );
808 $has_error++;
809 last;
810 }
811 $temp = $encoded;
812 }
813 $content = $temp unless( $has_error );
814 }
815
816 if( length( $content ) )
817 {
818 if( $self->is_binary( \$content ) )
819 {
820 $content = '(content is ' . length( $content ) . ' bytes of binary data)';
821 }
822 else
823 {
824 if( $maxlen && $body->length > $maxlen )
825 {
826 $content .= '...';
827 $chopped = $body->length - $maxlen;
828 }
829 $content =~ s/\\/\\\\/g;
830 $content =~ s/\t/\\t/g;
831 $content =~ s/\r/\\r/g;
832  
833 # no need for 3 digits in escape for these
834 $content =~ s/([\0-\11\13-\037])(?!\d)/sprintf('\\%o',ord($1))/eg;
835  
836 $content =~ s/([\0-\11\13-\037\177-\377])/sprintf('\\x%02X',ord($1))/eg;
837 $content =~ s/([^\12\040-\176])/sprintf('\\x{%X}',ord($1))/eg;
838  
839 # remaining whitespace
840 $content =~ s/( +)\n/("\\40" x length($1)) . "\n"/eg;
841 $content =~ s/(\n+)\n/("\\n" x length($1)) . "\n"/eg;
842 $content =~ s/\n\z/\\n/;
843 if( $content eq $no_content )
844 {
845 # escape our $no_content marker
846 $content =~ s/^(.)/sprintf('\\x%02X',ord($1))/eg;
847 }
848 }
849 }
850 else
851 {
852 $content = $no_content;
853 }
854 $content .= "\n(+ $chopped more bytes not shown)" if( $chopped );
855 }
856 elsif( !$self->part->is_empty )
857 {
858 my $boundary = $self->_prepare_multipart_headers;
859 # Multipart... form-data or mixed
860 if( defined( $toptype ) && $toptype eq 'multipart' )
861 {
862 my $boundary = $self->_prepare_multipart_headers();
863  
864 # Preamble. I do not think there should be any anyway for HTTP multipart
865 my $plines = $self->preamble;
866 if( defined( $plines ) )
867 {
868 # Defined, so output the preamble if it exists (avoiding additional
869 # newline as per ticket 60931)
870 $content .= join( '', @$plines ) . $crlf if( @$plines > 0 );
871 }
872 # Otherwise, no preamble.
873  
874 # Parts
875 foreach my $part ( $self->parts->list )
876 {
877 $content .= "--${boundary}${crlf}";
878 $content .= $part->dump( $opts );
879 # Trailing CRLF
880 $content .= $crlf;
881 }
882 $content .= "--${boundary}--${crlf}";
883  
884 # Epilogue
885 my $epilogue = $self->epilogue;
886 if( defined( $epilogue ) && !$epilogue->is_empty )
887 {
888 $content .= $epilogue->join( '' )->scalar;
889 if( $epilogue !~ /(?:\015?\012)\Z/ )
890 {
891 $content .= $crlf;
892 }
893 }
894 }
895 # Singlepart type with parts...
896 # This makes $ent->print handle message/rfc822 bodies
897 # when parse_nested_messages('NEST') is on [idea by Marc Rouleau].
898 else
899 {
900 my $need_sep = 0;
901 my $part;
902 foreach $part ( $self->parts->list )
903 {
904 if( $need_sep++ )
905 {
906 $content .= "${crlf}${crlf}";
907 }
908 $content .= $part->dump( $opts );
909 }
910 }
911 }
912  
913 my @dump;
914 push( @dump, $opts->{preheader} ) if( $opts->{preheader} );
915 my $start_line;
916 if( $self->http_message && ( $start_line = $self->http_message->start_line ) )
917 {
918 push( @dump, $start_line );
919 }
920 push( @dump, $self->headers->as_string, $content );
921  
922 my $dump = join( "\n", @dump, '' );
923 $dump =~ s/^/$opts->{prefix}/gm if( $opts->{prefix} );
924 return( $dump );
925 }
926  
927 sub dump_skeleton
928 {
929 my $self = shift( @_ );
930 my( $fh, $indent ) = @_;
931 $fh = select if( !$fh );
932 $indent = 0 if( !defined( $indent ) );
933 my $ind = ' ' x $indent;
934 my $part;
935 no strict 'refs';
936 my $crlf = CRLF;
937 my @first_line = ();
938 if( my $msg = $self->http_message )
939 {
940 if( $msg->isa( 'HTTP::Promise::Request' ) )
941 {
942 push( @first_line, $msg->method, $msg->uri, $msg->protocol );
943 }
944 else
945 {
946 push( @first_line, $msg->protocol, $msg->code, $msg->status );
947 }
948 print( $fh join( ' ', @first_line ), $crlf ) if( @first_line );
949 }
950 my $headers = $self->headers;
951 print( $fh $headers->as_string, $crlf ) || return( $self->error( $! ) );
952 my $body = $self->body;
953 if( $body )
954 {
955 if( $body->isa( 'HTTP::Promise::Body::File' ) )
956 {
957 print( $fh "${ind}Body is stored in a temporary file at '", $body->filename, "' and is ", $body->length, " bytes big.${crlf}" ) ||
958 return( $self->error( $! ) );
959 }
960 elsif( $body->isa( 'HTTP::Promise::Body::Form' ) )
961 {
962 print( $fh "${ind}Body is a x-www-form-urlencoded data with ", $body->length, " elements:\n", $body->dump ) ||
963 return( $self->error( $! ) );
964 }
965 else
966 {
967 print( $fh "${ind}Body is stored in memory and is ", $body->length, " bytes big.${crlf}" ) ||
968 return( $self->error( $! ) );
969 }
970 }
971 if( my $cd = $headers->content_disposition )
972 {
973 print( $fh "${ind}Body is encoded using $cd\n" ) || return( $self->error( $! ) );
974 }
975 my $filename = $self->headers->recommended_filename;
976 print( $fh $ind, "${ind}Recommended filename is: '${filename}'$crlf" ) if( $filename );
977  
978 # The parts
979 my $parts = $self->parts;
980 printf( $fh "${ind}This HTTP message has %d parts.${crlf}", $parts->length );
981 print( $fh $ind, "--\n" );
982 foreach $part ( @$parts )
983 {
984 $part->dump_skeleton( $fh, $indent + 1 );
985 }
986 return( $self );
987 }
988  
989 sub effective_type
990 {
991 my $self = shift( @_ );
992 if( @_ )
993 {
994 $self->_set_get_scalar_as_object( 'effective_type', @_ );
995 }
996 return( $self->_set_get_scalar_as_object( 'effective_type' ) || $self->mime_type );
997 }
998  
999 sub encode_body
1000 {
1001 my $self = shift( @_ );
1002 my $this = shift( @_ );
1003 return( $self->error( "Bad argument provided. encode_body() accepts only either an array of encodings or a string or something that stringifies." ) ) if( !defined( $this ) || ( !$self->_is_array( $this ) && ( ref( $this ) && !overload::Method( $this => '""' ) ) ) );
1004 my $encodings = $self->new_array( $self->_is_array( $this ) ? $this : [split( /[[:blank:]\h]*,[[:blank:]\h]*/, "${this}" )] );
1005 $self->_load_class( 'HTTP::Promise::Stream' ) || return( $self->error );
1006 my $body = $self->body;
1007 warn( "No encodings were provided to encode the HTTP body.\n" ) if( !scalar( @$encodings ) && warnings::enabled( 'HTTP::Promise' ) );
1008 # Nothing to do
1009 return( $self ) if( !$body );
1010 my $seen = {};
1011 if( $body->isa( 'HTTP::Promise::Body::File' ) )
1012 {
1013 my $f = $body;
1014 if( $f->is_empty )
1015 {
1016 warn( "HTTP Body file '$f' is empty, so there is nothing to encode\n" ) if( warnings::enabled( 'HTTP::Promise' ) );
1017 return( $self );
1018 }
1019 my $ext = $f->extension;
1020 foreach my $enc ( @$encodings )
1021 {
1022 next if( $enc eq 'identity' || $enc eq 'none' );
1023 next if( ++$seen->{ $enc } > 1 );
1024 my $s = HTTP::Promise::Stream->new( $f, encoding => $enc ) ||
1025 return( $self->pass_error( HTTP::Promise::Stream->error ) );
1026 if( $self->ext_vary )
1027 {
1028 my $enc_ext = HTTP::Promise::Stream->encoding2suffix( $enc ) ||
1029 return( $self->pass_error( HTTP::Promise::Stream->error ) );
1030 if( !$enc_ext->is_empty )
1031 {
1032 $ext .= '.' . $enc_ext->join( '.' )->scalar;
1033 }
1034 }
1035 my $tempfile = $self->new_tempfile( extension => $ext );
1036 my $len = $s->read( $tempfile );
1037 return( $self->pass_error( $s->error ) ) if( !defined( $len ) );
1038 return( $self->error( "The encoding pass on the HTTP body file source '$f' to target '$tempfile' with encoding '$enc' resulted in 0 byte encoded!" ) ) if( !$len );
1039 $f = $tempfile;
1040 }
1041 $body = HTTP::Promise::Body::File->new( $f ) ||
1042 return( $self->pass_error( HTTP::Promise::Body::File->error ) );
1043 $self->body( $body );
1044 }
1045 elsif( $body->isa( 'HTTP::Promise::Body::Scalar' ) )
1046 {
1047 my $temp = $body;
1048 if( $body->is_empty )
1049 {
1050 warn( "HTTP Body in memory is empty, so there is nothing to encode\n" ) if( warnings::enabled( 'HTTP::Promise' ) );
1051 return( $self );
1052 }
1053
1054 foreach my $enc ( @$encodings )
1055 {
1056 next if( $enc eq 'identity' || $enc eq 'none' );
1057 next if( ++$seen->{ $enc } > 1 );
1058 my $s = HTTP::Promise::Stream->new( $temp, encoding => $enc ) ||
1059 return( $self->pass_error( HTTP::Promise::Stream->error ) );
1060 my $encoded = $self->new_scalar;
1061 my $len = $s->read( $encoded );
1062 return( $self->pass_error( $s->error ) ) if( !defined( $len ) );
1063 return( $self->error( "The encoding pass on the HTTP body in memory with encoding '$enc' resulted in 0 byte encoded!" ) ) if( !$len );
1064 $temp = $encoded;
1065 }
1066 $body->set( $temp );
1067 $self->body( $body );
1068 }
1069 else
1070 {
1071 return( $self->error( "I do not know how to handle HTTP body object of class ", ref( $body ) ) );
1072 }
1073 return( $body );
1074 }
1075  
1076 sub epilogue { return( shift->_set_get_array_as_object( 'epilogue', @_ ) ); }
1077  
1078 sub ext_vary { return( shift->_set_get_boolean( 'ext_vary', @_ ) ); }
1079  
1080 # Credits: Christopher J. Madsen (IO::HTML)
1081 # Extract here, because I do not want to load all the modules
1082 sub guess_character_encoding
1083 {
1084 my $self = shift( @_ );
1085 my $opts = $self->_get_args_as_hash( @_ );
1086 my $data;
1087 if( exists( $opts->{content} ) && length( $opts->{content} ) )
1088 {
1089 return( $self->error( "Unsupported data type (", ref( $opts->{content} ), ")." ) ) if( ref( $opts->{content} ) && !$self->_is_scalar( $opts->{content} ) );
1090 $data = $self->_is_scalar( $opts->{content} ) ? $opts->{content} : \$opts->{content};
1091 }
1092 else
1093 {
1094 my $body = $self->body;
1095 return( '' ) if( !$body || $body->is_empty );
1096 my $buff;
1097 my $io = $body->open( '<', { binmode => 'raw' } ) ||
1098 return( $self->pass_error( $body->error ) );
1099 my $bytes = $io->read( $buff, 4096 );
1100 $io->close;
1101 return( $self->pass_error( $io->error ) ) if( !defined( $bytes ) );
1102 $data = \$buff;
1103 }
1104 return( '' ) if( $self->is_binary( $data ) );
1105  
1106 my $encoding;
1107 if( $$data =~ /^\xFe\xFF/ )
1108 {
1109 $encoding = 'UTF-16BE';
1110 }
1111 elsif( $$data =~ /^\xFF\xFe/ )
1112 {
1113 $encoding = 'UTF-16LE';
1114 }
1115 elsif( $$data =~ /^\xEF\xBB\xBF/ )
1116 {
1117 $encoding = 'utf-8-strict';
1118 }
1119  
1120 # try decoding as UTF-8
1121 if( !defined( $encoding ) )
1122 {
1123 $self->_load_class( 'Encode' ) || return( $self->pass_error );
1124 my $test = Encode::decode( 'utf-8-strict', $$data, Encode::FB_QUIET );
1125 # end if valid UTF-8 with at least one multi-byte character:
1126 if( $$data =~ /^(?: # nothing left over
1127 | [\xC2-\xDF] # incomplete 2-byte char
1128 | [\xE0-\xEF] [\x80-\xBF]? # incomplete 3-byte char
1129 | [\xF0-\xF4] [\x80-\xBF]{0,2} # incomplete 4-byte char
1130 )\z/x and $test =~ /[^\x00-\x7F]/ )
1131 {
1132 $encoding = 'utf-8-strict';
1133 }
1134 }
1135 # end if testing for UTF-8
1136 if( defined( $encoding ) and
1137 $opts->{object} and
1138 !ref( $encoding ) )
1139 {
1140 $self->_load_class( 'Encode' ) || return( $self->pass_error );
1141 $encoding = Encode::find_encoding( $encoding );
1142 }
1143 return( defined( $encoding ) ? $encoding : '' );
1144 }
1145  
1146 sub header { return( shift->headers->header( @_ ) ); }
1147  
1148 sub headers { return( shift->_set_get_object_without_init( 'headers','HTTP::Promise::Headers', @_ ) ); }
1149  
1150 sub header_as_string { return( shift->headers->as_string( @_ ) ); }
1151  
1152 sub http_message { return( shift->_set_get_object_without_init( 'http_message', 'HTTP::Promise::Message', @_ ) ); }
1153  
1154 # Ref: <https://stackoverflow.com/questions/9956198/in-perl-how-can-i-can-check-if-an-encoding-specified-in-a-string-is-valid>
1155 sub io_encoding
1156 {
1157 my $self = shift( @_ );
1158 my $opts = $self->_get_args_as_hash( @_ );
1159 # body argument is necessary when content has been decoded, but not replaced with decode_body()
1160 # and then HTTP::Promise::Message::decoded_content calls io_encoding() to get the character encoding
1161 my $body = $opts->{body} // $self->body;
1162 my $headers = $self->headers;
1163 # Use cache if it exists
1164 if( !exists( $opts->{content} ) &&
1165 ( ( $opts->{charset_strict} && $self->{_io_encoding_strict_cached} ) ||
1166 ( !$opts->{charset_strict} && $self->{_io_encoding_cached} )
1167 ) &&
1168 $body &&
1169 $self->{_checksum_md5} eq $body->checksum_md5 )
1170 {
1171 return( $opts->{charset_strict} ? $self->{_io_encoding_strict_cached} : $self->{_io_encoding_cached} );
1172 }
1173 my $data;
1174 if( exists( $opts->{content} ) && length( $opts->{content} ) )
1175 {
1176 return( $self->error( "Unsupported data type (", ref( $opts->{content} ), ")." ) ) if( ref( $opts->{content} ) && !$self->_is_scalar( $opts->{content} ) );
1177 $data = $self->_is_scalar( $opts->{content} ) ? $opts->{content} : \$opts->{content};
1178 }
1179 else
1180 {
1181 # my $body = $self->body || return( '' );
1182 return( '' ) if( !$body );
1183 $self->{_checksum_md5} = $body->checksum_md5;
1184 my $io = $body->open( '<', { binmode => 'raw' } ) ||
1185 return( $self->pass_error( $body->error ) );
1186 my $buff;
1187 my $bytes = $io->read( $buff, 4096 );
1188 return( $self->pass_error( $io->error ) ) if( !defined( $bytes ) );
1189 return( '' ) if( !$bytes );
1190 $data = \$buff;
1191 }
1192 # return( '' ) if( $self->is_binary( $data ) );
1193
1194 my $enc;
1195 if( $headers->content_is_text || ( my $is_xml = $headers->content_is_xml ) )
1196 {
1197 my $charset = lc(
1198 $opts->{charset} ||
1199 $headers->content_type_charset ||
1200 $opts->{default_charset} ||
1201 # content_type_charset to tell content_charset to not try to call this method since we just called it.
1202 $self->content_charset( content => $data, content_type_charset => 0 ) ||
1203 'UTF-8'
1204 );
1205 if( $charset eq 'none' )
1206 {
1207 # leave it as is
1208 }
1209 elsif( $charset eq 'us-ascii' || $charset eq 'iso-8859-1' )
1210 {
1211 # if( $$content_ref =~ /[^\x00-\x7F]/ && defined &utf8::upgrade )
1212 if( $$data =~ /[^\x00-\x7F]/ )
1213 {
1214 $enc = 'utf-8';
1215 }
1216 }
1217 else
1218 {
1219 $self->_load_class( 'Encode' ) || return( $self->pass_error );
1220 # try-catch
1221 local $@;
1222 eval
1223 {
1224 my $test = Encode::decode( $charset, $$data, ( ( $opts->{charset_strict} ? Encode::FB_CROAK : 0 ) | Encode::LEAVE_SRC ) );
1225 $enc = $charset;
1226 };
1227 if( $@ )
1228 {
1229 my $retried = 0;
1230 if( $@ =~ /^Unknown encoding/ )
1231 {
1232 my $alt_charset = lc( $opts->{alt_charset} || '' );
1233 if( $alt_charset && $charset ne $alt_charset )
1234 {
1235 # Retry decoding with the alternative charset
1236 my $test = Encode::decode( $alt_charset, $$data, ( ( $opts->{charset_strict} ? Encode::FB_CROAK : 0 ) | Encode::LEAVE_SRC ) ) unless( $alt_charset eq 'none' );
1237 $retried++;
1238 $enc = $alt_charset;
1239 }
1240 }
1241 return( $self->error( $@ ) ) unless( $retried );
1242 }
1243 }
1244 }
1245 if( $opts->{charset_strict} )
1246 {
1247 $self->{_io_encoding_strict_cached} = $enc;
1248 }
1249 else
1250 {
1251 $self->{_io_encoding_cached} = $enc;
1252 }
1253 return( defined( $enc ) ? $enc : '' );
1254 }
1255  
1256 # <https://stackoverflow.com/questions/899206/how-does-perl-know-a-file-is-binary>
1257 # <https://github.com/morungos/perl-Data-Binary/blob/master/lib/Data/Binary.pm>
1258 # "The "-T" and "-B" tests work as follows. The first block or so of the file is examined to see if it is valid UTF-8 that includes non-ASCII characters. If so, it's a "-T" file.
1259 # Otherwise, that same portion of the file is examined for odd characters such as strange control codes or characters with the high bit set. If more than a third of the characters are strange, it's a "-B" file; otherwise it's a "-T" file.
1260 # Also, any file containing a zero byte in the examined portion is considered a binary file. (If executed within the scope of a use locale which includes "LC_CTYPE", odd characters are anything that isn't a printable nor space in the current locale.) If "-T" or "-B" is used on a filehandle, the current IO buffer is examined rather than the first block. Both "-T" and "-B" return true on an empty file, or a file at EOF when testing a filehandle. Because you have to read a file to do the "-T" test, on most occasions you want to use a "-f" against the file first, as in "next unless -f $file && -T $file"."
1261 sub is_binary
1262 {
1263 my $self = shift( @_ );
1264 $self->_load_class( 'Encode' ) || return( $self->pass_error );
1265 my $data;
1266 if( @_ )
1267 {
1268 # We need to make a copy
1269 my $this = shift( @_ );
1270 return(0) if( !defined( $this ) || !length( "$this" ) );
1271 return( $self->error( "Bad argument. You can only provide a string or a scalar reference." ) ) if( ref( $this ) && !$self->_is_scalar( $this ) );
1272 $data = ref( $this ) ? $this : \$this;
1273 }
1274 else
1275 {
1276 my $body = $self->body;
1277 return(0) if( !$body || $body->is_empty );
1278 my $buff;
1279 my $io = $body->open( '<', { binmode => 'raw' } ) ||
1280 return( $self->pass_error( $body->error ) );
1281 my $bytes = $io->read( $buff, 4096 );
1282 $io->close;
1283 return( $self->pass_error( $io->error ) ) if( !defined( $bytes ) );
1284 warn( "Body is ", $body->length, " bytes big, but somehow I could not read ny bytes out of it.\n" ) if( !$bytes && warnings::enabled( 'HTTP::Promise' ) );
1285 return(0) if( !$bytes );
1286 $data = \$buff;
1287 }
1288
1289 # There are various method to check if the data is or contains binary data
1290 # perl's -B function is very cautious and will lean on the false positive.
1291 # Data::Binary implements the perl algorithm, but still yield false positive if, for example,
1292 # there is even 1 \0 in the data
1293 # The most reliable yet is to use module Encode with the die flag on upon error and catch it.
1294
1295 # Has the utf8 bit been set?
1296 # Then, let's try to encode it into utf-8
1297 if( utf8::is_utf8( $$data ) )
1298 {
1299 eval
1300 {
1301 Encode::encode( 'utf-8', $$data, ( Encode::FB_CROAK | Encode::LEAVE_SRC ) );
1302 };
1303 return( $@ ? 1 : 0 );
1304 }
1305 # otherwise, let's try to decode this into perl's internal utf8 representation
1306 # else
1307 # {
1308 # eval
1309 # {
1310 # Encode::decode( 'utf8', $$data, ( Encode::FB_CROAK | Encode::LEAVE_SRC ) );
1311 # };
1312 # }
1313 # return( $@ ? 1 : 0 );
1314  
1315 return(1) if( index( $$data, "\c@" ) != -1 );
1316 my $length = length( $$data );
1317 my $odd = ( $$data =~ tr/\x01\x02\x03\x04\x05\x06\x07\x09\x0b\x0c\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f//d );
1318 # Detecting >=128 and non-UTF-8 is interesting. Note that all UTF-8 >=128 has several bytes with
1319 # >=128 set, so a quick test is possible by simply checking if any are >=128. However, the count
1320 # from that is typically wrong, if this is binary data, it'll not have been decoded. So we do this
1321 # in two steps.
1322  
1323 my $copy = $$data;
1324 if( ( $copy =~ tr[\x80-\xff][]d ) > 0 )
1325 {
1326 my $modified = Encode::decode_utf8( $$data, Encode::FB_DEFAULT );
1327 my $substitions = ( $modified =~ tr/\x{fffd}//d );
1328 $odd += $substitions;
1329 }
1330 return(1) if( ( $odd / $length ) > 0.34 );
1331 return(0);
1332 }
1333  
1334 sub is_body_on_file
1335 {
1336 my $self = shift( @_ );
1337 my $body = $self->body;
1338 return(0) if( !$body || $body->is_empty );
1339 return( $self->_is_a( $body => 'HTTP::Promise::Body::File' ) );
1340 }
1341  
1342 sub is_body_in_memory
1343 {
1344 my $self = shift( @_ );
1345 my $body = $self->body;
1346 return(0) if( !$body || $body->is_empty );
1347 return( $self->_is_a( $body => 'HTTP::Promise::Body::Scalar' ) );
1348 }
1349  
1350 # Convenience
1351 sub is_decoded
1352 {
1353 my $self = shift( @_ );
1354 if( @_ )
1355 {
1356 my $bool = shift( @_ );
1357 return( !$self->is_encoded( !$bool ) );
1358 }
1359 else
1360 {
1361 return( !$self->is_encoded );
1362 }
1363 }
1364  
1365 sub is_encoded { return( shift->_set_get_boolean( 'is_encoded', @_ ) ); }
1366  
1367 sub is_multipart
1368 {
1369 my $self = shift( @_ );
1370 # no head, so no MIME type!
1371 $self->headers or return;
1372 my $mime_type = $self->headers->type;
1373 return(0) if( !defined( $mime_type ) || !length( $mime_type ) );
1374 return( substr( lc( $mime_type ), 0, 9 ) eq 'multipart' ? 1 : 0 );
1375 }
1376  
1377 sub is_text { return( !shift->is_binary( @_ ) ); }
1378  
1379 sub make_boundary { return( Data::UUID->new->create_str ); }
1380 # sub make_boundary
1381 # {
1382 # my $self = shift( @_ );
1383 # # my $uuid = $self->_uuid;
1384 # my $uuid = Data::UUID->new;
1385 # my $boundary = $uuid->create_str;
1386 # return( $boundary );
1387 # }
1388  
1389 sub make_multipart
1390 {
1391 my $self = shift( @_ );
1392 my $subtype = shift( @_ );
1393 my $opts = $self->_get_args_as_hash( @_ );
1394 my $tag;
1395 $subtype ||= 'form-data';
1396 my $force = $opts->{force};
1397  
1398 # Trap for simple case: already a multipart?
1399 return( $self ) if( $self->is_multipart and !$force );
1400 my $headers = $self->headers;
1401
1402  
1403 # Rip out our guts, and spew them into our future part.
1404 # part is a shallow copy
1405 # my $part = bless( {%$self} => ref( $self ) );
1406 # my $part = $self->new(
1407 # headers => $headers->clone,
1408 # ( $self->body ? ( body => $self->body ) : () ),
1409 # debug => $self->debug,
1410 # );
1411 #
1412 # if( my $msg = $self->http_message )
1413 # {
1414 # my $clone = $msg->clone( clone_entity => 0 );
1415 # $clone->entity( $part );
1416 # $part->http_message( $clone );
1417 # }
1418 # $part->parts( $self->parts );
1419
1420 my $part = $self->clone;
1421
1422 # my $part = $self->clone;
1423 # lobotomize ourselves!
1424 # %$self = ();
1425 # clone the headers
1426  
1427 # Remove content headers from top-level, and set it up as a multipart
1428 my $removed = $headers->remove_content_headers;
1429 my $ct = $headers->new_field( 'Content-Type' => "multipart/${subtype}" ) ||
1430 return( $self->pass_error( $headers->error ) );
1431 $ct->boundary( $self->make_boundary );
1432 my $ct_string = $ct->as_string;
1433 $headers->header( 'Content-Type' => "${ct_string}" );
1434  
1435 # Remove non-content headers from the part
1436 $removed = $self->new_array;
1437 foreach $tag ( grep{ !/^content-/i } $part->headers->header_field_names )
1438 {
1439 $part->headers->delete( $tag );
1440 $removed->push( $tag );
1441 }
1442 $self->parts->reset;
1443 $self->add_part( $part ) if( $part->body || $part->parts->length );
1444 return( $self );
1445 }
1446  
1447 sub make_singlepart
1448 {
1449 my $self = shift( @_ );
1450 # Trap for simple cases:
1451 # already a singlepart?
1452 return( $self ) if( !$self->is_multipart );
1453 # can this even be done?
1454 return(0) if( $self->parts > 1 );
1455  
1456 # Get rid of all our existing content info
1457 my $tag;
1458 foreach $tag ( grep{ /^content-/i } $self->headers->header_field_names )
1459 {
1460 $self->headers->delete( $tag );
1461 }
1462  
1463 # one part
1464 if( $self->parts->length == 1 )
1465 {
1466 my $part = $self->parts->index(0);
1467 # Populate ourselves with any content info from the part:
1468 foreach $tag ( grep{ /^content-/i } $part->headers->header_field_names )
1469 {
1470 $self->headers->add( $tag => $_ ) for( $part->headers->get( $tag ) );
1471 }
1472  
1473 # Save reconstructed headers, replace our guts, and restore header:
1474 my $new_head = $self->headers;
1475 # shallow copy is ok!
1476 %$self = %$part;
1477 $self->headers( $new_head );
1478  
1479 # One more thing: the part *may* have been a multi with 0 or 1 parts!
1480 return( $self->make_singlepart( @_ ) ) if( $self->is_multipart );
1481 }
1482 # no parts!
1483 else
1484 {
1485 $self->headers->mime_attr( 'Content-type' => 'text/plain' ); ### simple
1486 }
1487 return( $self );
1488 }
1489  
1490 sub mime_type
1491 {
1492 my $self = shift( @_ );
1493 my $headers = $self->headers;
1494 return if( !defined( $headers ) );
1495 return( $headers->mime_type( @_ ) );
1496 }
1497  
1498 # NOTE name() is to associate a name for this entity for multipart/form-data
1499 sub name { return( shift->_set_get_scalar_as_object( 'name', @_ ) ); }
1500  
1501 sub new_body
1502 {
1503 my $self = shift( @_ );
1504 my $type = shift( @_ ) || 'scalar';
1505 my $map =
1506 {
1507 file => 'HTTP::Promise::Body::File',
1508 form => 'HTTP::Promise::Body::Form',
1509 scalar => 'HTTP::Promise::Body::Scalar',
1510 string => 'HTTP::Promise::Body::Scalar',
1511 };
1512 my $class = $map->{ $type } || return( $self->error( "Unsupported body type '$type'" ) );
1513 if( $type eq 'form' )
1514 {
1515 $self->_load_class( $class ) || return( $self->pass_error );
1516 }
1517 my $body = $class->new( @_ );
1518 return( $self->pass_error( $class->error ) ) if( !defined( $body ) );
1519 return( $body );
1520 }
1521  
1522 sub open
1523 {
1524 my $self = shift( @_ );
1525 my $body = $self->body;
1526 return( $self->error( "Unable to open the entity body, because none is currently set." ) ) if( !$body );
1527 my $io = $body->open( @_ ) ||
1528 return( $self->pass_error( $body->error ) );
1529 return( $io );
1530 }
1531  
1532 sub output_dir { return( shift->_set_get_file( 'output_dir', @_ ) ); }
1533  
1534 # An array of HTTP::Promise::Entity objects
1535 sub parts { return( shift->_set_get_array_as_object( '_parts', @_ ) ); }
1536  
1537 sub preamble { return( shift->_set_get_array_as_object( 'preamble', @_ ) ); }
1538  
1539 sub print
1540 {
1541 my $self = shift( @_ );
1542 my $out = shift( @_ );
1543 my $opts = $self->_get_args_as_hash( @_ );
1544 my $eol = $opts->{eol} || $HTTP::Promise::Entity::BOUNDARY_DELIMITER || CRLF;
1545 $out = select if( !defined( $out ) );
1546 $out = Symbol::qualify( $out, scalar( caller ) ) unless( ref( $out ) );
1547 $self->_load_class( 'HTTP::Promise::IO' ) || return( $self->error );
1548 my $io = $self->_is_a( $out => 'HTTP::Promise::IO' )
1549 ? $out
1550 : HTTP::Promise::IO->new( $out, debug => $self->debug );
1551 return( $self->pass_error( HTTP::Promise::IO->error ) ) if( !defined( $io ) );
1552 $opts->{eol} = $eol;
1553 # The start-line
1554 $self->print_start_line( $io, $opts ) || return( $self->pass_error );
1555 # The headers
1556 $self->print_header( $io, $opts ) || return( $self->pass_error );
1557 $io->print( $eol ) ||
1558 return( $self->error( "Unable to print to filehandle provided '$io': $!" ) );
1559 # The body
1560 $self->print_body( $io, ( scalar( keys( %$opts ) ) ? $opts : () ) ) || return( $self->pass_error );
1561 return( $self );
1562 }
1563  
1564 sub print_body
1565 {
1566 my $self = shift( @_ );
1567 my $out = shift( @_ );
1568 my $opts = $self->_get_args_as_hash( @_ );
1569 return( $self->error( "Filehandle provided ($out) is not a proper filehandle and its not a HTTP::Promise::IO object." ) ) if( !$self->_is_glob( $out ) && !$self->_is_a( $out => 'HTTP::Promise::IO' ) );
1570 $out ||= select;
1571 my $mime_type = $self->mime_type;
1572 my $toptype;
1573 $toptype = [split( '/', lc( $mime_type ), 2 )]->[0] if( defined( $mime_type ) );
1574 # my $crlf = $HTTP::Promise::Entity::BOUNDARY_DELIMITER || CRLF;
1575 my $crlf = $opts->{eol} || $HTTP::Promise::Entity::BOUNDARY_DELIMITER || CRLF;
1576  
1577 # Multipart... form-data or mixed
1578 if( defined( $toptype ) && $toptype eq 'multipart' )
1579 {
1580 my $boundary = $self->_prepare_multipart_headers();
1581  
1582 # Preamble. I do not think there should be any anyway for HTTP multipart
1583 my $plines = $self->preamble;
1584 if( defined( $plines ) )
1585 {
1586 # Defined, so output the preamble if it exists (avoiding additional
1587 # newline as per ticket 60931)
1588 $out->print( join( $crlf, @$plines ) . $crlf ) if( @$plines > 0 );
1589 }
1590 # Otherwise, no preamble.
1591  
1592 # Parts
1593 foreach my $part ( $self->parts->list )
1594 {
1595 $out->print( "--${boundary}${crlf}" ) ||
1596 return( $self->error( "Unable to print request body to filehandle provided '$out': $!" ) );
1597 $part->print( $out ) ||
1598 return( $self->error( "Unable to print request body to filehandle provided '$out': $!" ) );
1599 # Trailing CRLF
1600 $out->print( $crlf ) ||
1601 return( $self->error( "Unable to print request body to filehandle provided '$out': $!" ) );
1602 }
1603 $out->print( "--${boundary}--${crlf}" ) ||
1604 return( $self->error( "Unable to print request body to filehandle provided '$out': $!" ) );
1605  
1606 # Epilogue
1607 my $epilogue = $self->epilogue;
1608 if( defined( $epilogue ) && !$epilogue->is_empty )
1609 {
1610 $out->print( $epilogue->join( $crlf )->scalar ) ||
1611 return( $self->error( "Unable to print request body to filehandle provided '$out': $!" ) );
1612 if( $epilogue !~ /(?:\015?\012)\Z/ )
1613 {
1614 $out->print( $crlf ) ||
1615 return( $self->error( "Unable to print request body to filehandle provided '$out': $!" ) );
1616 }
1617 }
1618 }
1619 # Singlepart type with parts...
1620 # This makes $ent->print handle message/rfc822 bodies
1621 # when parse_nested_messages('NEST') is on [idea by Marc Rouleau].
1622 elsif( !$self->parts->is_empty )
1623 {
1624 my $need_sep = 0;
1625 my $part;
1626 my $parts = $self->parts;
1627 # foreach $part ( $self->parts->list )
1628 foreach $part ( @$parts )
1629 {
1630 if( $need_sep++ )
1631 {
1632 $out->print( "${crlf}${crlf}" ) ||
1633 return( $self->error( "Unable to print request body to filehandle provided '$out': $!" ) );
1634 }
1635 $part->print( $out ) ||
1636 return( $self->error( "Unable to print request body to filehandle provided '$out': $!" ) );
1637 }
1638 }
1639 # Singlepart type, or no parts: output body...
1640 else
1641 {
1642 if( $self->body )
1643 {
1644 $self->print_bodyhandle( $out, ( scalar( keys( %$opts ) ) ? $opts : () ) ) ||
1645 return( $self->pass_error );
1646 }
1647 }
1648 return( $self );
1649 }
1650  
1651 sub print_bodyhandle
1652 {
1653 my $self = shift( @_ );
1654 my $out = shift( @_ );
1655 my $opts = $self->_get_args_as_hash( @_ );
1656 $out ||= select;
1657 return( $self->error( "Filehandle provided ($out) is not a proper filehandle and its not a HTTP::Promise::IO object." ) ) if( !$self->_is_glob( $out ) && !$self->_is_a( $out => 'HTTP::Promise::IO' ) );
1658  
1659 my $encoding = $self->headers->content_encoding;
1660 if( $encoding &&
1661 !$self->is_encoded &&
1662 ( !exists( $opts->{no_encode} ) ||
1663 ( exists( $opts->{no_encode} ) && !$opts->{no_encode} )
1664 ) )
1665 {
1666 $self->encode_body( $encoding ) || return( $self->pass_error );
1667 $self->is_encoded(1);
1668 }
1669 my $params = {};
1670 $params->{binmode} = $opts->{binmode} if( exists( $opts->{binmode} ) && $opts->{binmode} );
1671 # An opportunity here to specify the io layer, such as utf-8
1672 my $io = $self->open( 'r', ( scalar( keys( %$params ) ) ? $params : () ) ) || return( $self->pass_error );
1673 my $buff;
1674 while( $io->read( $buff, 8192 ) )
1675 {
1676 $out->print( $buff ) ||
1677 return( $self->error( "Unable to print request body to filehandle provided '$out': $!" ) );
1678 }
1679 $io->close;
1680 return( $self );
1681 }
1682  
1683 sub print_header { shift->headers->print( @_ ); }
1684  
1685 # NOTE: An entity is encapsulated inside either a request or a response.
1686 # See rfc7230, section 3.1 <https://tools.ietf.org/html/rfc7230#section-3.1>
1687 sub print_start_line
1688 {
1689 my $self = shift( @_ );
1690 my $out = shift( @_ );
1691 $out ||= select;
1692 return( $self->error( "Filehandle provided ($out) is not a proper filehandle and its not a HTTP::Promise::IO object." ) ) if( !$self->_is_glob( $out ) && !$self->_is_a( $out => 'HTTP::Promise::IO' ) );
1693 my $opts = $self->_get_args_as_hash( @_ );
1694 my $eol = $opts->{eol} || CRLF;
1695 if( my $msg = $self->http_message )
1696 {
1697 my $sl = $msg->start_line;
1698 return( $self ) unless( length( $sl ) );
1699 $out->print( $sl . $eol );
1700 }
1701 return( $self );
1702 }
1703  
1704 sub purge
1705 {
1706 my $self = shift( @_ );
1707 # purge me
1708 $self->body->purge if( $self->body );
1709 # recurse
1710 $_->purge for( $self->parts->list );
1711 return( $self );
1712 }
1713  
1714 sub save_file
1715 {
1716 my $self = shift( @_ );
1717 my $fname = shift( @_ );
1718 my $type = $self->headers->type;
1719 return( '' ) if( lc( substr( $type, 0, 10 ) ) eq 'multipart/' );
1720 unless( defined( $fname ) && length( "$fname" ) )
1721 {
1722 my $headers = $self->headers;
1723 if( my $val = $headers->content_disposition )
1724 {
1725 my $cd = $headers->new_field( 'Content-Disposition' => "$val" );
1726 return( $self->pass_error( $headers->error ) ) if( !defined( $cd ) );
1727 if( my $orig_name = $cd->filename )
1728 {
1729 my $f = $self->new_file( $orig_name );
1730 my $ext = $f->extension;
1731 my $base = $f->basename( ( defined( $ext ) && length( $ext ) ) ? $ext : () );
1732
1733 my @unsafe = map( quotemeta( $_ ), qw/ < > “ ‘ % ; ) ( & + $ [ ] : ./ );
1734 push( @unsafe, "\r", "\n", ' ', '/' );
1735 $base =~ s/(?<!\\)\.\.(?!\.)//g;
1736 local $" = '|';
1737 $base =~ s/(@unsafe)//g;
1738 unless( $ext )
1739 {
1740 # Guessing extension
1741 my $mime_type = $headers->mime_type( $DEFAULT_MIME_TYPE || 'application/octet-stream' );
1742 $self->_load_class( 'HTTP::Promise::MIME' ) || return( $self->pass_error );
1743 my $mime = HTTP::Promise::MIME->new;
1744 $ext = $mime->suffix( $mime_type );
1745 return( $self->pass_error( $mime->error ) ) if( !defined( $ext ) );
1746 }
1747 $ext ||= 'dat';
1748 $self->_load_class( 'Module::Generic::File' ) || return( $self->pass_error );
1749 my $output_dir = $self->outputdir || Module::Generic::File->sys_tmpdir;
1750 $fname = $output_dir->child( join( '.', $base, $ext ) );
1751 }
1752 }
1753
1754 if( !defined( $fname ) || !length( $fname ) )
1755 {
1756 # Guessing extension
1757 my $mime_type = $headers->mime_type( $DEFAULT_MIME_TYPE || 'application/octet-stream' );
1758 $self->_load_class( 'HTTP::Promise::MIME' ) || return( $self->pass_error );
1759 my $mime = HTTP::Promise::MIME->new;
1760 my $ext = $mime->suffix( $mime_type );
1761 return( $self->pass_error( $mime->error ) ) if( !defined( $ext ) );
1762 $ext ||= 'dat';
1763 $fname = $self->new_tempfile( extension => $ext );
1764 }
1765 }
1766 if( my $enc = $self->headers->content_encoding )
1767 {
1768 $self->decode_body( $enc ) if( $self->is_encoded );
1769 }
1770 my $f = $self->_is_a( $fname => 'Module::Generic::File' ) ? $fname : $self->new_file( "$fname" );
1771 my $io = $f->open( '+>', { binmode => 'raw', autoflush => 1 } ) ||
1772 return( $self->pass_error( $f->error ) );
1773 # Pass no_encode to ensure the file does not get automatically encoded
1774 $self->print_body( $io, no_encode => 1 ) || return( $self->pass_error );
1775 $io->close;
1776 return( $f );
1777 }
1778  
1779 sub stringify { return( shift->as_string( @_ ) ); }
1780  
1781 sub stringify_body { return( shift->body_as_string( @_ ) ); }
1782  
1783 sub stringify_header { return( shift->headers->as_string( @_ ) ); }
1784  
1785 sub suggest_encoding
1786 {
1787 my $self = shift( @_ );
1788 my $mime_type = $self->effective_type;
1789 my $toptype;
1790 $toptype = [split( '/', $mime_type, 2 )]->[0] if( defined( $mime_type ) );
1791 # Defaults to 200Kb
1792 my $threshold = $self->compression_min;
1793 my $rule = {qw(
1794 text/css gzip
1795 text/html gzip
1796 text/plain gzip
1797 text/x-component gzip
1798 application/atom+xml gzip
1799 application/javascript gzip
1800 application/json gzip
1801 application/pdf none
1802 application/rss+xml gzip
1803 application/vnd.ms-fontobject gzip
1804 application/x-font-opentype gzip
1805 application/x-font-ttf gzip
1806 application/x-javascript gzip
1807 application/x-web-app-manifest+json gzip
1808 application/xhtml+xml gzip
1809 application/xml gzip
1810 application/gzip none
1811 font/opentype gzip
1812 image/gif none
1813 image/jpeg none
1814 image/png none
1815 image/svg+xml gzip
1816 image/webp none
1817 image/x-icon none
1818 audio/mpeg none
1819 video/mp4 none
1820 audio/webm none
1821 video/webm none
1822 font/otf gzip
1823 font/ttf gzip
1824 font/woff2 none
1825
1826 )};
1827 # Already usually quite compressed, not much benefit compared to CPU penalty; we are
1828 # not in 1998 anymore :)
1829 # <http://web.archive.org/web/20190708231140/http://www.ibm.com/developerworks/web/library/wa-httpcomp/>
1830 # Also small files, like less than 1,500 bytes are a waste o time due to MTU max size
1831 # (https://en.wikipedia.org/wiki/Maximum_transmission_unit)
1832 # See also <https://httpd.apache.org/docs/2.4/mod/mod_deflate.html>
1833 # <https://webmasters.stackexchange.com/questions/31750/what-is-recommended-minimum-object-size-for-gzip-performance-benefits>
1834 if( exists( $rule->{ $mime_type } ) )
1835 {
1836 return( '' ) if( $rule->{ $mime_type } eq 'none' );
1837 return( $rule->{ $mime_type } ) if( !$threshold || $self->body->length >= $threshold );
1838 }
1839 elsif( $toptype eq 'image' ||
1840 $toptype eq 'video' ||
1841 $toptype eq 'audio' ||
1842 $toptype eq 'multipart' )
1843 {
1844 return( '' );
1845 }
1846 elsif( $toptype eq 'text' || $self->is_binary )
1847 {
1848 # Suggest gzip compression if it exceeds 200Kb
1849 return( 'gzip' ) if( !$threshold || $self->body->length >= $threshold );
1850 }
1851 return( '' );
1852 }
1853  
1854 sub textual_type
1855 {
1856 my $self = shift( @_ );
1857 return( $_[0] =~ m{^(text|message)(/|\Z)}i ? 1 : 0 );
1858 }
1859  
1860 sub _parts { return( shift->_set_get_array_as_object( '_parts', @_ ) ); }
1861  
1862 # NOTE: Used in both print_body() and dump()
1863 sub _prepare_multipart_headers
1864 {
1865 my $self = shift( @_ );
1866 my $mime_type = $self->mime_type;
1867 my $toptype;
1868 $toptype = [split( '/', lc( $mime_type ), 2 )]->[0] if( defined( $mime_type ) );
1869 my $boundary = $self->headers->multipart_boundary;
1870 # Ensure we have a boundary set.
1871 # This is the same code as in HTTP::Promise::Headers::as_string, but since
1872 # print_body() may be called separately, we need to check here too if a boundary
1873 # has been set.
1874 unless( $boundary )
1875 {
1876 $boundary = $self->make_boundary;
1877 my $ct = $self->headers->new_field( 'Content-Type' => $self->headers->content_type );
1878 $ct->boundary( $boundary );
1879 $self->headers->content_type( "$ct" );
1880 }
1881 # Parts
1882 # For reporting to the caller only when there are some issues.
1883 my $n = 0;
1884 # for generated part name, by default
1885 my $auto_name = 'part0';
1886 foreach my $part ( $self->parts->list )
1887 {
1888 ++$n;
1889 # If this is a multipart/form-data, ensure we have a part name, or isse a warning
1890 my $name;
1891 if( $mime_type eq 'multipart/form-data' )
1892 {
1893 $name = $part->name;
1894 if( !$name )
1895 {
1896 warn( "Warning: no part name set for this part No. ${n}\n" ) if( warnings::enabled( 'HTTP::Promise' ) );
1897 $name = ++$auto_name;
1898 $part->name( $name );
1899 }
1900 }
1901 elsif( $mime_type eq 'multipart/mixed' )
1902 {
1903 # remove any Content-Disposition used for multipart/form-data
1904 $part->headers->remove( 'Content-Disposition' );
1905 }
1906
1907 if( defined( $name ) )
1908 {
1909 my $content_disposition = $part->headers->content_disposition;
1910 if( defined( $content_disposition ) && $content_disposition->length )
1911 {
1912 # A simple check to save time from generating the Content-Disposition object
1913 if( $content_disposition->index( 'name=' ) == -1 ||
1914 $content_disposition->index( 'form-data' ) == -1 )
1915 {
1916 my $cd = $part->headers->new_field( 'Content-Disposition' => $part->headers->content_disposition );
1917 $cd->name( $name ) if( !length( $cd->name ) );
1918 $cd->disposition( 'form-data' );
1919 }
1920 }
1921 else
1922 {
1923 $part->headers->content_disposition( qq{form-data; name="${name}"} );
1924 }
1925 }
1926 }
1927 return( $boundary );
1928 }
1929  
1930 # NOTE: sub FREEZE is inherited
1931 sub FREEZE
1932 {
1933 my $self = CORE::shift( @_ );
1934 my $serialiser = CORE::shift( @_ ) // '';
1935 my $class = CORE::ref( $self );
1936 my $ref = $self->_obj2h;
1937 my %hash = %$ref;
1938 # We remove this to prevent a circular reference that CBOR::XS does not seem to be managing
1939 # This relation is re-created in HTTP::Promise::Message::THAW
1940 # It is safe to remove it, because 1) if it is a standalone HTTP::Promise::Entity object,
1941 # then it would not be set anyway, and 2) if it is part of an HTTP::Promise::Message, it
1942 # is going to be recreated.
1943 CORE::delete( @hash{ qw( http_message ) } ) unless( $serialiser ne 'CBOR' );
1944 # Return an array reference rather than a list so this works with Sereal and CBOR
1945 CORE::return( [$class, \%hash] ) if( $serialiser eq 'Sereal' && Sereal::Encoder->VERSION <= version->parse( '4.023' ) );
1946 # But Storable want a list with the first element being the serialised element
1947 CORE::return( $class, \%hash );
1948 }
1949  
1950 sub STORABLE_freeze { CORE::return( CORE::shift->FREEZE( @_ ) ); }
1951  
1952 sub STORABLE_thaw { CORE::return( CORE::shift->THAW( @_ ) ); }
1953  
1954 # NOTE: sub THAW is inherited
1955  
1956 1;
1957 # NOTE: POD
1958 __END__
1959  
1960 =encoding utf-8
1961  
1962 =head1 NAME
1963  
1964 HTTP::Promise::Entity - HTTP Entity Class
1965  
1966 =head1 SYNOPSIS
1967  
1968 use HTTP::Promise::Entity;
1969 my $this = HTTP::Promise::Entity->new || die( HTTP::Promise::Entity->error, "\n" );
1970  
1971 =head1 VERSION
1972  
1973 v0.2.2
1974  
1975 =head1 DESCRIPTION
1976  
1977 This class represents an HTTP entity, which is an object class containing an headers object and a body object. It is agnostic to the type of HTTP message (request or response) it is associated with and can be used recurrently, such as to represent a part in a multipart HTTP message. Its purpose is to provide an API to access and manipulate and HTTP message entity.
1978  
1979 Here is how it fits in overall relation with other classes.
1980
1981 +-------------------------+ +--------------------------+
1982 | | | |
1983 | HTTP::Promise::Request | | HTTP::Promise::Response |
1984 | | | |
1985 +------------|------------+ +-------------|------------+
1986 | |
1987 | |
1988 | |
1989 | +------------------------+ |
1990 | | | |
1991 +--- HTTP::Promise::Message |---+
1992 | |
1993 +------------|-----------+
1994 |
1995 |
1996 +------------|-----------+
1997 | |
1998 | HTTP::Promise::Entity |
1999 | |
2000 +------------|-----------+
2001 |
2002 |
2003 +------------|-----------+
2004 | |
2005 | HTTP::Promise::Body |
2006 | |
2007 +------------------------+
2008  
2009 =head1 CONSTRUCTOR
2010  
2011 =head2 new
2012  
2013 This instantiate a new L<HTTP::Promise::Entity> object and returns it. It takes the following options, which can also be set or retrieved with their related method.
2014  
2015 =over 4
2016  
2017 =item * C<compression_min>
2018  
2019 Integer. Size threshold beyond which the associated body can be compressed. This defaults to 204800 (200Kb). Set it to 0 to disable it.
2020  
2021 =item * C<effective_type>
2022  
2023 String. The effective mime-type. Default to C<undef>
2024  
2025 =item * C<epilogue>
2026  
2027 An array reference of strings to be added after the headers and before the parts in a multipart message. Each array reference entry is treated as one line. This defaults to C<undef>
2028  
2029 =item * C<ext_vary>
2030  
2031 Boolean. Setting this to a true value and this will have L</decode_body> and L</encode_body> change the entity body file extension to reflect the encoding or decoding applied.
2032  
2033 See L</ext_vary> for an example.
2034  
2035 =item * C<headers>
2036  
2037 This is an L<HTTP::Promise::Headers> object. This defaults to C<undef>
2038  
2039 =item * C<is_encoded>
2040  
2041 Boolean. This is a flag used to determine whether the related entity body is decoded or not. This defaults to C<undef>
2042  
2043 See also L<HTTP::Promise::Headers/content_encoding>
2044  
2045 =item * C<output_dir>
2046  
2047 This is the path to the directory used when extracting body to files on the filesystem. This defaults to C<undef>
2048  
2049 =item * C<preamble>
2050  
2051 An array reference of strings to be added after all the parts in a multipart message. Each array reference entry is treated as one line. This defaults to C<undef>
2052  
2053 =back
2054  
2055 =head1 METHODS
2056  
2057 =head2 add_part
2058  
2059 Provided with an L<HTTP::Promise::Entity> object, and this will add it to the stack of parts for this entity.
2060  
2061 It returns the part added, or upon error, sets an L<error|Module::Generic/error> and returns C<undef>.
2062  
2063 =head2 as_form_data
2064  
2065 If the entity is of type C<multipart/form-data>, this will transform all of its parts into an L<HTTP::Promise::Body::Form::Data> object.
2066  
2067 It returns the new L<HTTP::Promise::Body::Form::Data> object upon success, or 0 if there was nothing to be done i the entity is not C<multipart/form-data> for example, or upon error, sets an L<error|Module::Generic/error> and returns C<undef>.
2068  
2069 Note that this is memory savvy, because even though it breaks down the parts into an L<HTTP::Promise::Body::Form::Data> object, original entity body that were stored on file remain on file. Each of the L<HTTP::Promise::Body::Form::Data> entry is a field name and its value is an L<HTTP::Promise::Body::Form::Field> object. Thus you could access data such as:
2070  
2071 my $form = $ent->as_form_data;
2072 my $name = $form->{fullname}->value;
2073 if( $form->{picture}->file )
2074 {
2075 say "Picture is stored on file.";
2076 }
2077 elsif( $form->{picture}->value->length )
2078 {
2079 say "Picture is in memory.";
2080 }
2081 else
2082 {
2083 say "There is no data.";
2084 }
2085  
2086 say "Content-Type for this form-data is: ", $form->{picture}->headers->content_type;
2087  
2088 =head2 as_string
2089  
2090 This returns a L<scalar object|Module::Generic::Scalar> containing a string representation of the message entity.
2091  
2092 It takes an optional string parameter containing an end of line separator, which defaults to C<\015\012>.
2093  
2094 Internally, this calls L</print>.
2095  
2096 If an error occurred, it set an L<error|Module::Generic/error> and returns C<undef>.
2097  
2098 Be mindful that because this returns a scalar object, it means the entire HTTP message entity is loaded into memory, which, depending on the content size, can potentially be big and thus take a lot of memory.
2099  
2100 You may want to check the body size first using: C<$ent->body->length> for example if this is not a multipart entity.
2101  
2102 =head2 attach
2103  
2104 Provided with a list of parameters and this add the created part entity to the stack of entity parts.
2105  
2106 This will transform the current entity into a multipart, if necessary, by calling L</make_multipart>
2107  
2108 Since it calls L</build> internally to build the message entity, see L</build> for the list of supported parameters.
2109  
2110 It returns the newly added L<part object|HTTP::Promise::Entity> upon success, or upon error, sets an L<error|Module::Generic/error> and returns C<undef>.
2111  
2112 =head2 body
2113  
2114 Sets or gets this entity L<body object|HTTP::Promise::Body>.
2115  
2116 =head2 body_as_array
2117  
2118 This returns an L<array object|Module::Generic::Array> object containing body lines with each line terminated by an end-of-line sequence, which is optional and defaults to C<\015\012>.
2119  
2120 Upon error, sets an L<error|Module::Generic/error> and returns C<undef>.
2121  
2122 =head2 body_as_string
2123  
2124 This returns a L<scalar object|Module::Generic::Scalar> containing a string representation of the message body.
2125  
2126 =head2 build
2127  
2128 my $ent = HTTP::Promise::Entity->new(
2129 encoding => 'gzip',
2130 type => 'text/plain',
2131 data => 'Hello world',
2132 );
2133 my $ent = HTTP::Promise::Entity->new(
2134 encoding => 'guess',
2135 type => 'text/plain',
2136 data => '/some/where/file.txt',
2137 );
2138  
2139 This takes an hash or hash reference of parameters and build a new L<HTTP::Promise::Entity>.
2140  
2141 It returns the newly created L<entity object|HTTP::Promise::Entity> object upon success, or upon error, sets an L<error|Module::Generic/error> and returns C<undef>.
2142  
2143 Supported arguments are:
2144  
2145 =over 4
2146  
2147 =item * C<boundary>
2148  
2149 The part boundary to be used if the entity is of type multipart.
2150  
2151 =item * C<data>
2152  
2153 The entity body content. If this is provided, the entity body will be an L<HTTP::Promise::Body::Scalar> object.
2154  
2155 =item * C<debug>
2156  
2157 An integer representing the level of debugging output. Defaults to 0.
2158  
2159 =item * C<disposition>
2160  
2161 A string representing the C<Content-Disposition>, such as C<form-data>. This defaults to C<inline>.
2162  
2163 =item * C<encoding>
2164  
2165 String. A comma-separated list of content encodings used in order you want the entity body to be encoded.
2166  
2167 For example: C<gzip, base64> or C<brotli>
2168  
2169 See L<HTTP::Promise::Stream> for a list of supported encodings.
2170  
2171 If C<encoding> is C<guess>, this will call L</suggest_encoding> to find a suitable encoding, if any at all.
2172  
2173 =item * C<filename>
2174  
2175 The C<filename> attribute value of a C<Content-Disposition> header value, if any.
2176  
2177 If the filename provided contains 8 bit characters like unicode characters, this will be detected and the filename will be encoded according to L<rfc2231|https://tools.ietf.org/html/rfc2231>
2178  
2179 See also L<HTTP::Promise::Headers/content_disposition> and L<HTTP::Promise::Headers::ContentDisposition>
2180  
2181 =item * C<path>
2182  
2183 The filepath to the content to be used as the entity body. This is useful if the body size is big and you do not want to load it in memory.
2184  
2185 =item * C<type>
2186  
2187 String. The entity mime-type. This defaults to C<text/plain>
2188  
2189 If the type is set to C<multipart/form-data> or C<multipart/mixed>, or any other multipart type, this will automatically create a boundary, which is basically a UUID generated with the XS module L<Data::UUID>
2190  
2191 =back
2192  
2193 =head2 compression_min
2194  
2195 Integer. This is the body size threshold in bytes beyond which this will make the encoding of the entity body possible. You can set this to zero to deactivate it.
2196  
2197 =head2 content_charset
2198  
2199 This will try to guess the character set of the body and returns a string the character encoding found, if any, or upon error, sets an L<error|Module::Generic/error> and returns C<undef>. If nothing was found, it will return an empty string.
2200  
2201 It takes an optional hash or hash reference of options.
2202  
2203 Supported options are;
2204  
2205 =over 4
2206  
2207 =item * C<content>
2208  
2209 A string or scalar reference of some or all of the body data to be checked. If this is not provided, 4Kb of data will be read from the body to guess the character encoding.
2210  
2211 =back
2212  
2213 =head2 decode_body
2214  
2215 This takes a coma-separated list of encoding or an array reference of encodings, and an optional hash or hash reference of options and decodes the entity body.
2216  
2217 It returns the L<body object|HTTP::Promise::Body> upon success, and upon error, sets an L<error|Module::Generic/error> and returns C<undef>.
2218  
2219 Supported options are:
2220  
2221 =over 4
2222  
2223 =item * C<raise_error>
2224  
2225 Boolean. When set to true, this will cause this method to die upon error.
2226  
2227 =item * C<replace>
2228  
2229 Boolean. If true, this will replace the body content with the decoded version. Defaults to true.
2230  
2231 =back
2232  
2233 What this method does is instantiate a new L<HTTP::Promise::Stream> object for each encoding and pass it the data whether as a scalar reference if the data are in-memory body, or a file, until all decoding have been applied.
2234  
2235 When C<deflate> is one of the encoding, it will try to use L<IO::Uncompress::Inflate> to decompress data. However, some server encode data with C<deflate> but omit the zlib headers, which makes L<IO::Uncompress::Inflate> fail. This is detected and trapped and C<rawdeflate> is used as a fallback.
2236  
2237 =head2 dump
2238  
2239 This dumps the entity data into a string and returns it. It will encode the body if not yet encoded and will escape control and space characters, and show in hexadecimal representation the body content, so that even binary data is safe to dump.
2240  
2241 It takes some optional arguments, which are:
2242  
2243 =over 4
2244  
2245 =item * C<maxlength>
2246  
2247 Max body length to include in the dump.
2248  
2249 =item * C<no_content>
2250  
2251 The string to use when there is no content, i.e. when the body is empty.
2252  
2253 =back
2254  
2255 =head2 dump_skeleton
2256  
2257 This method is more for debugging, or to get a peek at the entity structure. This takes a filehandle to print the result to.
2258  
2259 This returns the current L<entity object|HTTP::Promise::Entity> on success, and upon error, sets an L<error|Module::Generic/error> and returns C<undef>.
2260  
2261 =head2 effective_type
2262  
2263 This set or get the effective mime-type. In assignment mode, this simply stores whatever mie-type you provide and in retrieval mode, this retrieve the value previously set, or by default the value returned from L</mime_type>
2264  
2265 =head2 encode_body
2266  
2267 This encode the entity body according to the encodings provided either as a comma-separated string or an array reference of encodings.
2268  
2269 The way it does this is to instantiate a new L<HTTP::Promise::Stream> object for each encoding and pass it the latest entity body.
2270  
2271 The resulting encoded body replaces the original one.
2272  
2273 It returns the L<entity body|HTTP::Promise::Body> upon success, and upon error, sets an L<error|Module::Generic/error> and returns C<undef>.
2274  
2275 =head2 epilogue
2276  
2277 Sets or gets an array of epilogue lines. An C<epilogue> is lines of text added after the last part of a C<multipart> message.
2278  
2279 This returns an L<array object|Module::Generic::Array>
2280  
2281 =head2 ext_vary
2282  
2283 Boolean. Setting this to a true value and this will have L</decode_body> and L</encode_body> change the entity body file extension to reflect the encoding or decoding applied.
2284  
2285 For example, if the entity body is stored in a text file C</tmp/DDAB03F0-F530-11EC-8067-D968FDB3E034.txt>, applying L</encode_body> with C<gzip> will create a new body text file such as C</tmp/DE13000E-F530-11EC-8067-D968FDB3E034.txt.gz>
2286  
2287 =head2 guess_character_encoding
2288  
2289 This will try to guess the entity body character encoding.
2290  
2291 It returns the encoding found as a string, if any otherwise it returns an empty string (not undef), and upon error, sets an L<error|Module::Generic/error> and returns C<undef>.
2292  
2293 This method tries to guess variation of unicode character sets, such as C<UTF-16BE>, C<UTF-16LE>, and C<utf-8-strict>
2294  
2295 It takes some optional parameters:
2296  
2297 =over 4
2298  
2299 =item * C<content>
2300  
2301 A string or scalar reference of content data to perform the guessing against.
2302  
2303 If this is not provided, this method will read up to 4096 bytes of data from the body to perform the guessing.
2304  
2305 =back
2306  
2307 See also L</content_charset>
2308  
2309 =head2 header
2310  
2311 Set or get the value returned by calling L<HTTP::Promise::Headers/header>
2312  
2313 This is just a shortcut.
2314  
2315 =head2 headers
2316  
2317 Sets or get the L<entity headers object|HTTP::Promise::Headers>
2318  
2319 =head2 header_as_string
2320  
2321 Returns the entity headers as a string.
2322  
2323 =head2 http_message
2324  
2325 Sets or get the L<HTTP message object|HTTP::Promise::Message>
2326  
2327 =head2 io_encoding
2328  
2329 This tries hard to find out the character set of the entity body to be used with L<perlfunc/open> or L<perlfunc/binmode>
2330  
2331 It returns a string, possibly empty if nothing could be guessed, and upon error, sets an L<error|Module::Generic/error> and returns C<undef>.
2332  
2333 It takes the following optional parameters:
2334  
2335 =over 4
2336  
2337 =item * C<alt_charset>
2338  
2339 Alternative character set to be used if none other could be found nor worked.
2340  
2341 =item * C<body>
2342  
2343 The entity L<body object|HTTP::Promise::Body> to use.
2344  
2345 =item * C<charset>
2346  
2347 A string containing the charset you think is used and this will perform checks against it.
2348  
2349 =item * C<charset_strict>
2350  
2351 Boolean. If true, this will enable the guessing in more strict mode (using the C<FB_CROAK> flag on L<Encode>)
2352  
2353 =item * C<content>
2354  
2355 A string or a scalar reference of content data to the guessing against.
2356  
2357 =item * C<default_charset>
2358  
2359 The default charset to use when nothing else was found.
2360  
2361 =back
2362  
2363 =head2 is_binary
2364  
2365 This checks if the data provided, or by default this entity body is binary data or not.
2366  
2367 It returns true (1) if it is, and false (0) otherwise. It returns false if the data is empty.
2368  
2369 This performs the similar checks that perl does (see L<perlfunc/-T>
2370  
2371 It sets and L<error|Module::Generic/error> and return C<undef> upon error
2372  
2373 You can optionally provide some data either as a string or as a scalar reference.
2374  
2375 See also L</is_text>
2376  
2377 For example:
2378  
2379 my $bool = $ent->is_binary;
2380 my $bool = $ent->is_binary( $string_of_data );
2381 my $bool = $ent->is_binary( \$string_of_data );
2382  
2383 =head2 is_body_in_memory
2384  
2385 Returns true if the entity body is an L<HTTP::Promise::Body::Scalar> object, false otherwise.
2386  
2387 =head2 is_body_on_file
2388  
2389 Returns true if the entity body is an L<HTTP::Promise::Body::File> object, false otherwise.
2390  
2391 =head2 is_decoded
2392  
2393 Boolean. Set get the decoded status of the entity body.
2394  
2395 =head2 is_encoded
2396  
2397 Boolean. Set get the encoded status of the entity body.
2398  
2399 =head2 is_multipart
2400  
2401 Returns true if this entity is a multipart message or not.
2402  
2403 =head2 is_text
2404  
2405 This checks if the data provided, or by default this entity body is text data or not.
2406  
2407 It returns true (1) if it is, and false (0) otherwise. It returns true if the data is empty.
2408  
2409 It sets and L<error|Module::Generic/error> and return C<undef> upon error
2410  
2411 You can optionally provide some data either as a string or as a scalar reference.
2412  
2413 See also L</is_binary>
2414  
2415 For example:
2416  
2417 my $bool = $ent->is_text;
2418 my $bool = $ent->is_text( $string_of_data );
2419 my $bool = $ent->is_text( \$string_of_data );
2420  
2421 =head2 make_boundary
2422  
2423 Returns a uniquely generated multipart boundary created using L<Data::UUID>
2424  
2425 =head2 make_multipart
2426  
2427 This transforms the current entity into the first part of a <multipart/form-data> HTTP message.
2428  
2429 For HTTP request, C<multipart/form-data> is the only valid C<Content-Type> for sending multiple data. L<rfc7578 in section 4.3|https://tools.ietf.org/html/rfc7578#section-4.3> states: "[RFC2388] suggested that multiple files for a single form field be transmitted using a nested "multipart/mixed" part. This usage is deprecated."
2430  
2431 See also this L<Stackoverflow discussion|https://stackoverflow.com/questions/36674161/http-multipart-form-data-multiple-files-in-one-input/41204533#41204533> and L<this one too|https://stackoverflow.com/questions/51575746/http-header-content-type-multipart-mixed-causes-400-bad-request>
2432  
2433 Of course, technically, nothing prevents an HTTP message (request or response) from being a C<multipart/mixed> or something else.
2434  
2435 This method takes a multipart subtype, such as C<form-data>, or C<mixed>, etc and creates a multipart entity of which this current entity will become the first part. If no multipart subtype is specified, this defaults to C<form-data>.
2436  
2437 It takes also an optional hash or hash reference of parameters.
2438  
2439 Valid parameters are:
2440  
2441 =over 4
2442  
2443 =item * C<force>
2444  
2445 Boolean. Forces the creation of a multipart even when the current entity is already a multipart.
2446  
2447 This would have the effect of having the current entity become an embedded multipart into a new multipart entity.
2448  
2449 =back
2450  
2451 It returns the current entity object, modified, upon success, or upon error, sets an L<error|Module::Generic/error> and returns C<undef>.
2452  
2453 =head2 make_singlepart
2454  
2455 This transform the current entity into a simple, i.e. no multipart, message entity.
2456  
2457 It returns false, but not C<undef> if this contains more than one part. It returns the current object upon success, or if this is already a simple entity message, or upon error, sets an L<error|Module::Generic/error> and returns C<undef>.
2458  
2459 =head2 mime_type
2460  
2461 Returns this entity mime-type by calling L<HTTP::Promise::Headers/mime_type> and passing it whatever arguments were provided.
2462  
2463 =head2 name
2464  
2465 The name of this entity used for C<multipart/form-data> as defined in L<rfc7578|https://tools.ietf.org/html/rfc7578>
2466  
2467 =head2 new_body
2468  
2469 This is a convenient constructor to instantiate a new entity body. It takes a single argument, one of C<file>, C<form>, C<scalar> or C<string>
2470  
2471 =over 4
2472  
2473 =item * C<file>
2474  
2475 Returns a new L<HTTP::Promise::Body::File> object
2476  
2477 =item * C<form>
2478  
2479 Returns a new L<HTTP::Promise::Body::Form> object
2480  
2481 =item * C<scalar> or C<string>
2482  
2483 Returns a new L<HTTP::Promise::Body::Scalar> object
2484  
2485 =back
2486  
2487 The constructor of each of those classes are passed whatever argument is provided to this method (except, of course, the initial argument).
2488  
2489 For example:
2490  
2491 my $body = $ent->new_body( file => '/some/where/file.txt' );
2492 my $body = $ent->new_body( string => 'Hello world!' );
2493 my $body = $ent->new_body( string => \$scalar );
2494 # Same, but using indistinctly 'scalar'
2495 my $body = $ent->new_body( scalar => \$scalar );
2496  
2497 It returns the newly instantiated object upon success, or upon error, sets an L<error|Module::Generic/error> and returns C<undef>.
2498  
2499 =head2 open
2500  
2501 This calls C<open> on the entity body object, if any, and passing it whatever argument was provided.
2502  
2503 It returns the resulting L<filehandle object|Module::Generic::File::IO>, or upon error, sets an L<error|Module::Generic/error> and returns C<undef>.
2504  
2505 =head2 output_dir
2506  
2507 Sets or gets the path to the directory used to store extracted files, when applicable.
2508  
2509 =head2 parts
2510  
2511 Sets or gets the L<array object|Module::Generic::Array> of entity part objects.
2512  
2513 =head2 preamble
2514  
2515 Sets or gets the L<array object|Module::Generic::Array> of preamble lines. C<preamble> is the lines of text that precedes the first part in a multipart message. Normally, this is never used in HTTP parlance.
2516  
2517 =head2 print
2518  
2519 Provided with a filehandle, or an L<HTTP::Promise::IO> object, and an hash or hash reference of options and this will print the current entity with all its parts, if any.
2520  
2521 What this does internally is:
2522  
2523 =over 4
2524  
2525 =item 1. Call L</print_start_line>
2526  
2527 =item 2. Call L</print_header>
2528  
2529 =item 3. Call L</print_body>
2530  
2531 =back
2532  
2533 The only supported option is C<eol> which is the string to be used as a new line terminator. This is printed out just right after printing the headers. This defaults to C<\015\012>, which is C<\r\n>
2534  
2535 It returns the current entity object upon success, or upon error, sets an L<error|Module::Generic/error> and returns C<undef>.
2536  
2537 =head2 print_body
2538  
2539 Provided with a filehandle, or an L<HTTP::Promise::IO> object, and an hash or hash reference of options and this will print the current entity body. This is possibly is a no-op if there is no entity body.
2540  
2541 If the entity is a multipart message, this will call L</print> on all its L<entity parts|HTTP::Promise::Entity>.
2542  
2543 It returns the current entity object upon success, or upon error, sets an L<error|Module::Generic/error> and returns C<undef>.
2544  
2545 =head2 print_bodyhandle
2546  
2547 Provided with a filehandle, or an L<HTTP::Promise::IO> object, and an hash or hash reference of options and this will print the current entity body.
2548  
2549 This will first encode the body by calling L</encode> if encodings are set and the entity body is not yet marked as being encoded with L</is_encoded>
2550  
2551 Supported options are:
2552  
2553 =over 4
2554  
2555 =item * C<binmode>
2556  
2557 The character encoding to use for PerlIO when calling open.
2558  
2559 =back
2560  
2561 It returns the current entity object upon success, or upon error, sets an L<error|Module::Generic/error> and returns C<undef>.
2562  
2563 =head2 print_header
2564  
2565 This calls L<HTTP::Promise::Headers/print>, passing it whatever arguments were provided, and returns whatever value is returned from this method call. This is basically a convenient shortcut.
2566  
2567 =head2 print_start_line
2568  
2569 Provided with a filehandle, and an hash or hash reference of options and this will print the message C<start line>, if any.
2570  
2571 A message C<start line> in HTTP parlance is the first line of a request or response, so something like:
2572  
2573 GET / HTTP/1.0
2574  
2575 or for a response:
2576  
2577 HTTP/1.0 200 OK
2578  
2579 It returns the current entity object upon success, or upon error, sets an L<error|Module::Generic/error> and returns C<undef>.
2580  
2581 =head2 purge
2582  
2583 This calls C<purge> on the body object, if any, and calls it also on every parts.
2584  
2585 It returns the current entity object upon success, or upon error, sets an L<error|Module::Generic/error> and returns C<undef>.
2586  
2587 =head2 save_file
2588  
2589 Provided with an optional filepath and this will save the body to it unless this is an HTTP multipart message.
2590  
2591 If no explicit filepath is provided, this will try to guess one from the C<Content-Disposition> header value, possibly striping it of any dangerous characters and making it a complete path using L</output_dir>
2592  
2593 If no suitable filename could be found, ultimately, this will use a generated one using L<Module::Generic/new_tempfile> inherited by this class.
2594  
2595 The file extension will be guessed from the entity body mime-type by checking the C<Content-Type> header or by looking directly at the entity body data using L<HTTP::Promise::MIME> that uses the XS module L<File::MMagic::XS> to perform the job.
2596  
2597 If the entity body is encoded, it will decode it before saving it to the resulting filepath.
2598  
2599 It returns the L<file object|Module::Generic::File> upon success, or upon error, sets an L<error|Module::Generic/error> and returns C<undef>.
2600  
2601 =head2 stringify
2602  
2603 This is an alias for L</as_string>
2604  
2605 =head2 stringify_body
2606  
2607 This is an alias for L</body_as_string>
2608  
2609 =head2 stringify_header
2610  
2611 This is an alias for L<HTTP::Promise::Headers/as_string>
2612  
2613 =head2 suggest_encoding
2614  
2615 Based on the entity body mime-type, this will guess what encoding is appropriate.
2616  
2617 It does not provide any encoding for image, audio or video files who are usually already compressed and if the body size is below the threshold set with L</compression_min>.
2618  
2619 This returns the encoding as a string upon success, an empty string if no suitable encoding could be found, or upon error, sets an L<error|Module::Generic/error> and returns C<undef>.
2620  
2621 =head2 textual_type
2622  
2623 Returns true if this entity mime-type starts with C<text>, such as C<text/plain> or C<text/html> or starts with C<message>, such as C<message/http>
2624  
2625 =head1 THREAD-SAFETY
2626  
2627 L<HTTP::Promise::Entity> is thread-safe for all operations, as it operates on per-object state and uses thread-safe external libraries.
2628  
2629 =head1 AUTHOR
2630  
2631 Jacques Deguest E<lt>F<jack@deguest.jp>E<gt>
2632  
2633 =head1 SEE ALSO
2634  
2635 =over 4
2636
2637 =item L<rfc2616 section 3.7.2 Multipart Types|http://tools.ietf.org/html/rfc2616#section-3.7.2>
2638
2639 =item L<rfc2046 section 5.1.1 Common Syntax|http://tools.ietf.org/html/rfc2046#section-5.1.1>
2640
2641 =item L<rfc2388 multipart/form-data|http://tools.ietf.org/html/rfc2388>
2642
2643 =item L<rfc2045|https://tools.ietf.org/html/rfc2045>
2644
2645 =back
2646  
2647 L<Mozilla documentation on Content-Disposition and international filename|https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition> and L<other Mozilla documentation|https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types.>
2648  
2649 L<Wikipedia|https://en.wikipedia.org/wiki/MIME#Multipart_messages>
2650  
2651 L<On Unicode|https://perldoc.perl.org/Encode::Unicode>
2652  
2653 L<HTTP::Promise>, L<HTTP::Promise::Request>, L<HTTP::Promise::Response>, L<HTTP::Promise::Message>, L<HTTP::Promise::Entity>, L<HTTP::Promise::Headers>, L<HTTP::Promise::Body>, L<HTTP::Promise::Body::Form>, L<HTTP::Promise::Body::Form::Data>, L<HTTP::Promise::Body::Form::Field>, L<HTTP::Promise::Status>, L<HTTP::Promise::MIME>, L<HTTP::Promise::Parser>, L<HTTP::Promise::IO>, L<HTTP::Promise::Stream>, L<HTTP::Promise::Exception>
2654  
2655 =head1 COPYRIGHT & LICENSE
2656  
2657 Copyright(c) 2022 DEGUEST Pte. Ltd.
2658  
2659 All rights reserved
2660 This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
2661  
2662 =cut