blib/lib/Google/Ads/Common/ReportUtils.pm untested

filter: Statementstmt 0.0% 0 / 137 Branchbran 0.0% 0 / 52 Conditioncond 0.0% 0 / 7 MC/DCmcdc 0.0% 0 / 4 Subroutinesub 0.0% 0 / 21 Podpod 0.0% 0 / 3 totaltotal 0.0% 0 / 224 CC 27 SCAR 57.3
CC
27
Cov
0%
download_report
600.0
__extract_xml_error
12.0
__extract_legacy_error
6.0
CRAP 308.2
1 # Copyright 2011, Google Inc. All Rights Reserved.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14  
15 package Google::Ads::Common::ReportUtils;
16  
17 use strict;
18 use utf8;
19 use version;
20  
21 # The following needs to be on one line because CPAN uses a particularly hacky
22 # eval() to determine module versions.
23 use Google::Ads::Common::Constants; our $VERSION = ${Google::Ads::Common::Constants::VERSION};
24  
25 use Google::Ads::Common::ReportDownloadError;
26  
27 use File::stat;
28 use HTTP::Request;
29 use HTTP::Status qw(:constants);
30 use LWP::UserAgent;
31 use MIME::Base64;
32 use POSIX;
33 use URI::Escape;
34 use XML::Simple;
35  
36 use constant REPORT_DOWNLOAD_URL => "%s/api/adwords/reportdownload?__rd=%s";
37 use constant ADHOC_REPORT_DOWNLOAD_URL => "%s/api/adwords/reportdownload/%s";
38 use constant CLIENT_EMAIL_MAX_VERSION => "201101";
39 use constant XML_ERRORS_MIN_VERSION => "201209";
40 use constant LWP_DEFAULT_TIMEOUT => 300; # 5 minutes.
41  
42 sub download_report {
43 my ($report_definition, $client, $file_path, $server,
44 $return_money_in_micros, $timeout) = @_;
45  
46 # Build report downlad url.
47 $server = $server ? $server : $client->get_alternate_url();
48 $server = $server =~ /\/$/ ? substr($server, 0, -1) : $server;
49 my $url;
50  
51 if (isdigit($report_definition)) {
52 $url = sprintf(REPORT_DOWNLOAD_URL, $server, $report_definition);
53 } else {
54 # Assuming is a ReportDefinition object
55 $url = sprintf(ADHOC_REPORT_DOWNLOAD_URL, $server, $client->get_version());
56 }
57  
58 my $lwp = LWP::UserAgent->new();
59  
60 # Setting HTTP user-agent and gzip compression.
61 my $can_accept = HTTP::Message::decodable;
62 my $gzip_support = $can_accept =~ /gzip/i;
63 $lwp->default_header("Accept-Encoding" => scalar $can_accept);
64 $lwp->agent($client->get_user_agent() . ($gzip_support ? " gzip" : ""));
65  
66 # Set agent timeout.
67 $lwp->timeout($timeout ? $timeout : LWP_DEFAULT_TIMEOUT);
68  
69 # Set the authorization headers.
70 my @headers = ();
71  
72 my $auth_handler = $client->_get_auth_handler();
73  
74 if ($auth_handler->isa("Google::Ads::Common::OAuth2BaseHandler")) {
75 # In this case we use the client OAuth2
76 push @headers, "Authorization" => "Bearer " .
77 $auth_handler->get_access_token();
78 } else {
79 # In this case we use the client login header.
80 push @headers, "Authorization" => "GoogleLogin auth=" .
81 $auth_handler->__get_auth_token();
82 }
83  
84 my $current_version = $client->get_version();
85 $current_version =~ s/[^0-9]//g;
86 if ($client->get_client_id()) {
87 if ($client->get_client_id() =~ /@/) {
88 if ($current_version > CLIENT_EMAIL_MAX_VERSION) {
89 if ($client->get_die_on_faults()) {
90 die("Version " . $client->get_version() .
91 " has no support for identifying clients by email.");
92 } else {
93 warn("Version " . $client->get_version() .
94 " has no support for identifying clients by email.");
95 }
96 } else {
97 push @headers, "clientEmail" => $client->get_client_id();
98 }
99 } else {
100 push @headers, "clientCustomerId" => $client->get_client_id();
101 }
102 } elsif ($current_version <= CLIENT_EMAIL_MAX_VERSION &&
103 $client->get_email()) {
104 push @headers, "clientEmail" => $client->get_email();
105 }
106  
107 # Set other headers.
108 if (defined $return_money_in_micros) {
109 push @headers, "returnMoneyInMicros" => $return_money_in_micros ?
110 "true" : "false";
111 }
112 push @headers, "developerToken" => $client->get_developer_token();
113  
114 # Read proxy configuration for the enviroment.
115 $lwp->env_proxy();
116  
117 # Request the report.
118 my $request;
119 my $format;
120 if (isdigit($report_definition)) {
121 $request = HTTP::Request->new("GET", $url, \@headers);
122 } elsif (ref($report_definition) eq "HASH") {
123 push @headers, "Content-Type" => "application/x-www-form-urlencoded";
124 $request = HTTP::Request->new("POST", $url, \@headers, "__rdquery=" .
125 uri_escape_utf8($report_definition->{query}) . "&__fmt=" .
126 uri_escape_utf8($report_definition->{format}));
127 $format = $report_definition->{format};
128 } else {
129 push @headers, "Content-Type" => "application/x-www-form-urlencoded";
130 $request = HTTP::Request->new("POST", $url, \@headers, "__rdxml=" .
131 uri_escape_utf8("<reportDefinition>" . $report_definition .
132 "</reportDefinition>"));
133 $format = $report_definition->get_downloadFormat() . "";
134 }
135  
136 my $response;
137 if ($file_path) {
138 ($file_path) = glob($file_path);
139 if (!$gzip_support) {
140 # If not gzip support then we can stream directly to a file.
141 $response = $lwp->request($request, $file_path);
142 } else {
143 my $mode = ">:utf8";
144 if ($format =~ /^GZIPPED|PDF/) {
145 # Binary format can't dump as UTF8.
146 $mode = ">";
147 }
148 open(FH, $mode, $file_path) or warn "Can't write to '$file_path': $!";
149 $response = $lwp->request($request);
150 # Need to decode in a file.
151 print FH $response->decoded_content();
152 close FH;
153 }
154 } else {
155 $response = $lwp->request($request);
156 }
157 if ($response->code == HTTP_OK) {
158 if ($file_path) {
159 open(FILE, "<", $file_path) or return undef;
160 my $result = <FILE>;
161 close(FILE);
162 if (__extract_legacy_error($result)) {
163 return undef;
164 }
165 return stat($file_path)->size;
166 } else {
167 return $response->decoded_content();
168 }
169 } elsif ($response->code == HTTP_BAD_REQUEST) {
170 my $result = $response->decoded_content();
171 if ($current_version >= XML_ERRORS_MIN_VERSION) {
172 return __extract_xml_error($result);
173 } else {
174 __extract_legacy_error($result);
175 return undef;
176 }
177 } else {
178 warn("Report download failed with code '" . $response->code .
179 "' and message '" . $response->message . ".");
180 return undef;
181 }
182 }
183  
184 sub __extract_legacy_error {
185 my $report_result = shift;
186 if ($report_result =~ m/^!!![^|]*\|\|\|([^|]*)\|\|\|([^?]*)\?\?\?/) {
187 warn("Report download failed with error " . $2);
188 return $2;
189 }
190 return undef;
191 }
192  
193 sub __extract_xml_error {
194 my $ref = XML::Simple->new()->XMLin(shift, ForceContent => 1);
195  
196 return Google::Ads::Common::ReportDownloadError->new({
197 type => $ref->{ApiError}->{type}->{content},
198 field_path => $ref->{ApiError}->{fieldPath}->{content} ?
199 $ref->{ApiError}->{fieldPath}->{content} : "",
200 trigger => $ref->{ApiError}->{trigger}->{content} ?
201 $ref->{ApiError}->{trigger}->{content} : ""
202 });
203 }
204  
205 return 1;
206  
207 =pod
208  
209 =head1 NAME
210  
211 Google::Ads::Common::ReportUtils
212  
213 =head1 SYNOPSIS
214  
215 use Google::Ads::Common::ReportUtils;
216  
217 Google::Ads::Common::ReportUtils::download_report($report_definition,
218 $client, $path);
219  
220 =head1 DESCRIPTION
221  
222 Google::Ads::Common::ReportUtils a collection of utility methods for working
223 with reports.
224  
225 =head1 SUBROUTINES
226  
227 =head2 download_report
228  
229 Downloads a new instance of an existing report definition. If the file_path
230 parameter is specified it will be downloaded to the file at that path, otherwise
231 it will be downloaded to memory and be returned as a string.
232  
233 =head3 Parameters
234  
235 =over
236  
237 =item *
238  
239 The report_definition parameter is either:
240 - the id of a pre-defined report to download
241 - a C<ReportDefinition> object to be defined and download on the fly
242 - a hash with an AWQL query and format. i.e. { query => 'query',
243 format => 'format' }
244  
245 In the case of a plain id then the regular download endpoint will be used to
246 download a pre-stored definition, otherwise the versioned download url endpoint
247 (based on the version of the given C<Client> object) will be used.
248  
249 =item *
250  
251 The client parameter is an instance of a valid L<Google::AdWords::Client>.
252  
253 =item *
254  
255 The file_path is an optional parameter that if given the subroutine will write
256 out the report to the given file path.
257  
258 =item *
259  
260 The server is an optional parameter that can be set to alter the URL from where
261 the report will be requested.
262  
263 =item *
264  
265 The return_money_in_micros is an optional parameter that can be set to alter
266 the output of money kind of fields in the report.
267  
268 =item *
269  
270 The timeout is an optional parameter that can be set to alter the default
271 time that the http client waits to get a response from the server. If not set,
272 the default timeout used is
273 L<Google::Ads::Common::ReportUtils::LWP_DEFAULT_TIMEOUT>.
274  
275 =back
276  
277 =head3 Returns
278  
279 If a file_path is given, the report gets saved to file and the file size is
280 returned, if not the report data itself is returned.
281  
282 =head3 Exceptions
283  
284 Starting with v201209 of the API a L<Google::Ads::Common::ReportDownloadError>
285 object will be returned in case of a download error. If not passing a
286 C<file_path> to dump the report then you must check if the return
287 isa("Google::Ads::Common::ReportDownloadError").
288  
289 Prior to v201209 a warn() will be issued if a report download error occurs.
290  
291 =head1 LICENSE AND COPYRIGHT
292  
293 Copyright 2011 Google Inc.
294  
295 Licensed under the Apache License, Version 2.0 (the "License");
296 you may not use this file except in compliance with the License.
297 You may obtain a copy of the License at
298  
299 http://www.apache.org/licenses/LICENSE-2.0
300  
301 Unless required by applicable law or agreed to in writing, software
302 distributed under the License is distributed on an "AS IS" BASIS,
303 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
304 See the License for the specific language governing permissions and
305 limitations under the License.
306  
307 =head1 AUTHOR
308  
309 David Torres E<lt>api.davidtorres at gmail.comE<gt>
310  
311 =head1 REPOSITORY INFORMATION
312  
313 $Rev: $
314 $LastChangedBy: $
315 $Id: $
316  
317 =cut