@@ -3,6 +3,7 @@ use Mojo::Base 'Mojo::EventEmitter';
3
3
4
4
# "Fry: Since when is the Internet about robbing people of their privacy?
5
5
# Bender: August 6, 1991."
6
+ use Carp qw( croak) ;
6
7
use Mojo::IOLoop;
7
8
use Mojo::Promise;
8
9
use Mojo::Util qw( monkey_patch term_escape) ;
@@ -48,6 +49,22 @@ sub DESTROY { shift->_cleanup unless ${^GLOBAL_PHASE} eq 'DESTRUCT' }
48
49
sub build_tx { shift -> transactor-> tx(@_ ) }
49
50
sub build_websocket_tx { shift -> transactor-> websocket(@_ ) }
50
51
52
+ sub download {
53
+ my ($self , $url , $path , $options ) = (shift , shift , shift , shift // {});
54
+
55
+ my $tx = _download_error($self -> transactor-> download($self -> head($url => $options -> {headers } // {}), $path ));
56
+ return $tx ? !!_download_error($self -> start($tx )) : 1;
57
+ }
58
+
59
+ sub download_p {
60
+ my ($self , $url , $path , $options ) = (shift , shift , shift , shift // {});
61
+
62
+ return $self -> head_p($url => $options -> {headers } // {})-> then(sub {
63
+ my $tx = _download_error($self -> transactor-> download(shift , $path ));
64
+ return $tx ? $self -> start_p($tx ) : 1;
65
+ })-> then(sub { ref $_ [0] ? !!_download_error($_ [0]) : $_ [0] });
66
+ }
67
+
51
68
sub start {
52
69
my ($self , $tx , $cb ) = @_ ;
53
70
@@ -213,6 +230,15 @@ sub _dequeue {
213
230
return $found ;
214
231
}
215
232
233
+ sub _download_error {
234
+ my $tx = shift ;
235
+
236
+ return $tx unless my $err = $tx -> error;
237
+ return undef if $err -> {incomplete_download } || $err -> {complete_download };
238
+ croak " $err ->{code} response: $err ->{message}" if $err -> {code };
239
+ croak " Connection error: $err ->{message}" ;
240
+ }
241
+
216
242
sub _error {
217
243
my ($self , $id , $err ) = @_ ;
218
244
my $tx = $self -> {connections }{$id }{tx };
@@ -748,6 +774,21 @@ a callback.
748
774
warn "Connection error: $err";
749
775
})->wait;
750
776
777
+ =head2 download
778
+
779
+ my $bool = $ua->download('https://example.com/test.tar.gz', '/home/sri/test.tar.gz');
780
+ my $bool = $ua->download('https://example.com/test.tar.gz', '/home/sri/test.tar.gz', {headers => {Accept => '*/*'}});
781
+
782
+ Download file from URL to local file, returns true once the file has been downloaded completely. Incomplete downloads
783
+ are resumed. Note that this method is B<EXPERIMENTAL > and might change without warning!
784
+
785
+ =head2 download_p
786
+
787
+ my $promise = $ua->download_p('https://example.com/test.tar.gz', '/home/sri/test.tar.gz');
788
+
789
+ Same as L</"download"> , but performs all requests non-blocking and returns a L<Mojo::Promise> object. Note that this
790
+ method is B<EXPERIMENTAL > and might change without warning!
791
+
751
792
=head2 get
752
793
753
794
my $tx = $ua->get('example.com');
0 commit comments