@@ -3,6 +3,7 @@ use Mojo::Base 'Mojo::EventEmitter';
33
44# "Fry: Since when is the Internet about robbing people of their privacy?
55# Bender: August 6, 1991."
6+ use Carp qw( croak) ;
67use Mojo::IOLoop;
78use Mojo::Promise;
89use Mojo::Util qw( monkey_patch term_escape) ;
@@ -48,6 +49,37 @@ sub DESTROY { shift->_cleanup unless ${^GLOBAL_PHASE} eq 'DESTRUCT' }
4849sub build_tx { shift -> transactor-> tx(@_ ) }
4950sub build_websocket_tx { shift -> transactor-> websocket(@_ ) }
5051
52+ sub download {
53+ my ($self , $url , $path , $options ) = @_ ;
54+ $options //= {};
55+
56+ my $tx = _download_error($self -> transactor-> download($self -> head($url => $options -> {headers } // {}), $path ));
57+ return $tx ? !!_download_error($self -> start($tx )) : 1;
58+ }
59+
60+ sub download_p {
61+ my ($self , $url , $path , $options ) = @_ ;
62+ $options //= {};
63+
64+ return $self -> head_p($url => $options -> {headers } // {})-> then(sub {
65+ my $tx = _download_error($self -> transactor-> download(shift , $path ));
66+ return $tx ? $self -> start_p($tx ) : 1;
67+ })-> then(sub {
68+ my $tx = shift ;
69+ return ref $tx ? !!_download_error($tx ) : $tx ;
70+ });
71+ }
72+
73+ sub _download_error {
74+ my $tx = shift ;
75+ if (my $err = $tx -> error) {
76+ return undef if $err -> {incomplete_download } || $err -> {complete_download };
77+ croak " $err ->{code} response: $err ->{message}" if $err -> {code };
78+ croak " Connection error: $err ->{message}" ;
79+ }
80+ return $tx ;
81+ }
82+
5183sub start {
5284 my ($self , $tx , $cb ) = @_ ;
5385
@@ -748,6 +780,21 @@ a callback.
748780 warn "Connection error: $err";
749781 })->wait;
750782
783+ =head2 download
784+
785+ my $bool = $ua->download('https://example.com/test.tar.gz', '/home/sri/test.tar.gz');
786+ my $bool = $ua->download('https://example.com/test.tar.gz', '/home/sri/test.tar.gz', {headers => {Accept => '*/*'}});
787+
788+ Download file from URL to local file, returns true once the file has been downloaded completely. Incomplete downloads
789+ are resumed. Note that this method is B<EXPERIMENTAL > and might change without warning!
790+
791+ =head2 download_p
792+
793+ my $promise = $ua->download_p('https://example.com/test.tar.gz', '/home/sri/test.tar.gz');
794+
795+ Same as L</"download"> , but performs all requests non-blocking and returns a L<Mojo::Promise> object. Note that this
796+ method is B<EXPERIMENTAL > and might change without warning!
797+
751798=head2 get
752799
753800 my $tx = $ua->get('example.com');
0 commit comments