| 1 | package WWW::Crawler::Mojo::UserAgent; | ||
| 2 | use strict; | ||
| 3 | use warnings; | ||
| 4 | use Mojo::Base 'Mojo::UserAgent'; | ||
| 5 | |||
| 6 | has credentials => sub {{}}; | ||
| 7 | has keep_credentials => 1; | ||
| 8 | |||
| 9 | sub new { | ||
| 10 | my $class = shift; | ||
| 11 | my $self = $class->SUPER::new(@_); | ||
| 12 | |||
| 13 | if ($self->keep_credentials) { | ||
| 14 | $self->on(start => sub { | ||
| 15 | my ($self, $tx) = @_; | ||
| 16 | my $url = $tx->req->url; | ||
| 17 | if ($url->is_abs) { | ||
| 18 | my $key = $url->scheme. '://'. $url->host. ':'. ($url->port || 80); | ||
| 19 | if ($url->userinfo) { | ||
| 20 | $self->credentials->{$key} = $url->userinfo; | ||
| 21 | } else { | ||
| 22 | $url->userinfo($self->credentials->{$key}); | ||
| 23 | } | ||
| 24 | } | ||
| 25 | }); | ||
| 26 | } | ||
| 27 | |||
| 28 | return $self; | ||
| 29 | } | ||
| 30 | |||
| 31 | 1; | ||
| 32 | |||
| 33 | =head1 NAME | ||
| 34 | |||
| 35 | WWW::Crawler::Mojo::UserAgent - Mojo::UserAgent sub class for userinfo storage | ||
| 36 | |||
| 37 | =head1 SYNOPSIS | ||
| 38 | |||
| 39 | my $ua = WWW::Crawler::Mojo::UserAgent->new; | ||
| 40 | $ua->keep_credentials(1); | ||
| 41 | $ua->credentials->{'http://example.com:80'} = 'jamadam:password'; | ||
| 42 | my $tx = $ua->get('http://example.com/'); | ||
| 43 | say $tx->req->url # http://jamadam:passowrd@example.com/ | ||
| 44 | |||
| 45 | =head1 DESCRIPTION | ||
| 46 | |||
| 47 | This class inherits Mojo::UserAgent and override start method for storing user | ||
| 48 | info | ||
| 49 | |||
| 50 | =head1 ATTRIBUTES | ||
| 51 | |||
| 52 | WWW::Crawler::Mojo::UserAgent inherits all attributes from Mojo::UserAgent. | ||
| 53 | |||
| 54 | =head2 keep_credentials | ||
| 55 | |||
| 56 | Set true to set the feature on. | ||
| 57 | |||
| 58 | $ua->keep_credentials(1); | ||
| 59 | |||
| 60 | =head2 credentials | ||
| 61 | |||
| 62 | Storage for credentials. | ||
| 63 | |||
| 64 | $ua->credentials->{'http://example.com:80'} = 'jamadam:password'; | ||
| 65 | |||
| 66 | =head1 METHODS | ||
| 67 | |||
| 68 | WWW::Crawler::Mojo::UserAgent inherits all methods from Mojo::UserAgent. | ||
| 69 | |||
| 70 | =head1 AUTHOR | ||
| 71 | |||
| 72 | Sugama Keita, E<lt>sugama@jamadam.comE<gt> | ||
| 73 | |||
| 74 | =head1 COPYRIGHT AND LICENSE | ||
| 75 | |||
| 76 | Copyright (C) Sugama Keita. | ||
| 77 | |||
| 78 | This program is free software; you can redistribute it and/or | ||
| 79 | modify it under the same terms as Perl itself. | ||
| 80 | |||
| 81 | =cut |