blib/lib/Aion/Surf.pm

filter: Statementstmt 94.2% 33 / 35 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 12 / 12 Podpod n/a totaltotal 95.7% 45 / 47 CC 1 SCAR 0.2
CC
1
Cov
94%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
↑ Summary
1 package Aion::Surf;
2 1 ▶use 5.22.0;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 1 ▶no strict; no warnings; no diagnostics;
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use common::sense;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 our $VERSION = "0.0.3";
7  
8 1 ▶use List::Util qw/pairmap/;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use LWP::UserAgent qw//;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 1 ▶use HTTP::Cookies qw//;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use Aion::Format::Json qw//;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 1 ▶use Aion::Format::Url qw//;
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 1 ▶use Exporter qw/import/;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 our @EXPORT = our @EXPORT_OK = grep {
16 ref \$Aion::Surf::{$_} eq "GLOB"
17 && *{$Aion::Surf::{$_}}{CODE}
18 && !/^(_|(NaN|import)\z)/n
19 } keys %Aion::Surf::;
20  
21  
22 #@category surf
23  
24 0 ▶use config TIMEOUT => 10;
Subroutine BEGIN: called CC=1 SCAR=2.6
25 use config FROM_IP => undef;
26 use config AGENT => q{Mozilla/5.0 (Macintosh; Intel Mac OS X 14_0) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15};
27  
28 our $ua = LWP::UserAgent->new;
29 $ua->agent(AGENT);
30 #$ua->env_proxy;
31 $ua->timeout(TIMEOUT);
32 $ua->local_address(FROM_IP) if FROM_IP;
33 $ua->cookie_jar(HTTP::Cookies->new);
34  
35 # Между вызовами делаем случайный интервал (для граббинга - чтобы не быть заблокированным за автоматические обращения)
36 our $SLEEP = 0;
37 our $LAST_REQUEST = Time::HiRes::time();
38 sub _sleep(;$) {
39 Time::HiRes::sleep(rand + .5) if Time::HiRes::time() - $LAST_REQUEST < 2;
40 $LAST_REQUEST = Time::HiRes::time();
41 }
42  
43 sub surf(@) {
44 my $method = $_[0] =~ /^(\w+)\z/ ? shift: "GET";
45 my $url = shift;
46 my $headers;
47 my $data = ref $_[0]? shift: undef;
48 $headers = $data, undef $data if $method =~ /^(GET|HEAD)\z/n;
49  
50 my %set = @_;
51  
52 if(exists $set{sleep}) {
53 my $sleep = delete $set{sleep};
54 } else {
55 _sleep if $SLEEP;
56 }
57  
58 my $query = delete $set{query};
59 if(defined $query) {
60 $url = join "", $url, $url =~ /\?/ ? "&": "?",
61 Aion::Format::Url::to_url_params $query;
62 }
63  
64 my $request = HTTP::Request->new($method => $url);
65  
66 my $validate_data = sub {
67 die "surf: data has already been provided!" if defined $data;
68 die "surf: sended data in $method!" if $method =~ /^(HEAD|GET)\z/;
69 };
70  
71 # Устанавливаем данные
72 my $json = delete $set{json};
73 $json = $data, undef $data if not defined $json and ref $data eq "HASH";
74 if(defined $json) {
75 $validate_data->();
76  
77 $request->header('Content-Type' => 'application/json; charset=utf-8');
78 $data = Aion::Format::Json::to_json $json;
79 utf8::encode($data) if utf8::is_utf8($data);
80 $request->content($data);
81 }
82  
83 my $form = delete $set{form};
84 $form = $data, undef $data if not defined $form and ref $data eq "ARRAY";
85 if(defined $form) {
86 $validate_data->();
87 $data = 1;
88  
89 $request->header('Content-Type' => 'application/x-www-form-urlencoded');
90 $request->content(Aion::Format::Url::to_url_params $form);
91 }
92  
93 if($headers = delete($set{headers}) // $headers) {
94 if(ref $headers eq 'HASH') {
95 $request->header($_, $headers->{$_}) for sort keys %$headers;
96 } else {
97 for my ($key, $val) (@$headers) {
98 $request->header($key, $val);
99 }
100 }
101 }
102  
103 if(my $cookie_href = delete $set{cookies}) {
104 my $jar = $ua->cookie_jar;
105 my $url_href = Aion::Format::Url::parse_url $url;
106 my $domain = $url_href->{domain};
107 $domain = "localhost.local" if $domain eq "localhost";
108  
109 $cookie_href = {@$cookie_href} if ref $cookie_href eq "ARRAY";
110  
111 for my $key (sort keys %$cookie_href) {
112  
113 my $av;
114 my $val = $cookie_href->{$key};
115 $av = $val, $val = shift @$av, $av = {@$av} if ref $val;
116  
117 $jar->set_cookie(
118 delete($a->{version}),
119 Aion::Format::Url::to_url_param $key
120 => Aion::Format::Url::to_url_param $val,
121 delete($av->{path}) // "/",
122 delete($av->{domain}) // $domain,
123 delete($av->{port}),
124 delete($av->{path_spec}),
125 delete($av->{secure}),
126 delete($av->{maxage}),
127 delete($av->{discard}),
128 $av
129 );
130 }
131 }
132  
133 my $response_set = delete $set{response};
134  
135 die "Unknown keys: " . join ", ", keys %set if keys %set;
136  
137 my $response = $ua->request($request);
138 $$response_set = $response if ref $response_set;
139  
140 return $response->is_success if $method eq "HEAD";
141  
142 my $content = $response->decoded_content;
143 eval { $content = Aion::Format::Json::from_json($content) } if $content =~ m!^\{!;
144  
145 $content
146 }
147  
148 sub head (;$) { my $x = @_ == 0? $_: shift; surf HEAD => ref $x? @{$x}: $x }
149 sub get (;$) { my $x = @_ == 0? $_: shift; surf GET => ref $x? @{$x}: $x }
150 sub post (@) { my $x = @_ == 0? $_: \@_; surf POST => ref $x? @{$x}: $x }
151 sub put (@) { my $x = @_ == 0? $_: \@_; surf PUT => ref $x? @{$x}: $x }
152 sub patch(@) { my $x = @_ == 0? $_: \@_; surf PATCH => ref $x? @{$x}: $x }
153 sub del (;$) { my $x = @_ == 0? $_: shift; surf DELETE => ref $x? @{$x}: $x }
154  
155  
156 use config TELEGRAM_BOT_TOKEN => undef;
157  
158 # Отправляет сообщение телеграм
159 sub chat_message($$) {
160 my ($chat_id, $message) = @_;
161  
162 my $ok = post "https://api.telegram.org/bot${\ TELEGRAM_BOT_TOKEN}/sendMessage", response => \my $response, json => {
163 chat_id => $chat_id,
164 text => $message,
165 disable_web_page_preview => 1,
166 parse_mode => 'Html',
167 };
168  
169 die $ok->{description} if !$ok->{ok};
170  
171 $ok
172 }
173  
174  
175 use config TELEGRAM_BOT_CHAT_ID => undef;
176 use config TELEGRAM_BOT_TECH_ID => undef;
177  
178 # Отправляет сообщение в телеграм-бот
179 sub bot_message(;$) { chat_message TELEGRAM_BOT_CHAT_ID, @_ == 0? $_: $_[0] }
180 # Отправляет сообщение в технический телеграм канал
181 sub tech_message(;$) { chat_message TELEGRAM_BOT_TECH_ID, @_ == 0? $_: $_[0] }
182  
183  
184 # Получает последние сообщения отправленные боту
185 sub bot_update() {
186 my @updates;
187  
188 for(my $offset = 0;;) {
189  
190 my $ok = post "https://api.telegram.org/bot${\ TELEGRAM_BOT_TOKEN}/getUpdates", json => {
191 offset => $offset,
192 };
193  
194 die $ok->{description} if !$ok->{ok};
195  
196 my $result = $ok->{result};
197 return \@updates if !@$result;
198  
199 push @updates, map $_->{message}, grep $_->{message}, @$result;
200  
201 $offset = $result->[$#$result]{update_id} + 1;
202 }
203 }
204  
205 1;
206  
207 __END__
↑ Summary