File: API.pm

package info (click to toggle)
libweb-api-perl 2.8-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 152 kB
  • sloc: perl: 719; makefile: 2
file content (1437 lines) | stat: -rw-r--r-- 34,890 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
package Web::API;

use 5.010001;
use Mouse::Role;

# ABSTRACT: A Simple base module to implement almost every RESTful API with just a few lines of configuration

our $VERSION = '2.8'; # VERSION

use LWP::UserAgent;
use HTTP::Cookies 6.04;
use Data::Printer colored => 1;
use XML::Simple;
use URI::Escape::XS qw/uri_escape uri_unescape/;
use JSON;
use URI;
use URI::QueryParam;
use Carp;
use Net::OAuth;
use Data::Random qw(rand_chars);
use Time::HiRes 'sleep';

$Net::OAuth::PROTOCOL_VERSION = Net::OAuth::PROTOCOL_VERSION_1_0A;

our $AUTOLOAD;

our %CONTENT_TYPE = (
    json => 'application/json',
    js   => 'application/json',
    xml  => 'text/xml',
);


requires 'commands';


has 'live_url' => (
    is      => 'rw',
    isa     => 'Str',
    lazy    => 1,
    builder => '_build_live_test_url',
);


has 'test_url' => (
    is      => 'rw',
    isa     => 'Str',
    lazy    => 1,
    builder => '_build_live_test_url',
);


has 'test' => (
    is      => 'rw',
    isa     => 'Bool',
    default => sub { 0 },
);


has 'api_key' => (
    is  => 'rw',
    isa => 'Str',
);


has 'user' => (
    is  => 'rw',
    isa => 'Str',
);


has 'api_key_field' => (
    is      => 'rw',
    isa     => 'Str',
    default => sub { 'key' },
);


has 'api_version' => (
    is      => 'rw',
    isa     => 'Int',
    default => sub { 1 },
);


has 'mapping' => (is => 'rw');


has 'wrapper' => (
    is      => 'rw',
    clearer => 'clear_wrapper',
);


has 'header' => (
    is      => 'rw',
    lazy    => 1,
    default => sub { {} },
);


has 'auth_type' => (
    is      => 'rw',
    isa     => 'Str',
    default => sub { 'none' },
);


has 'auth_header' => (
    is      => 'rw',
    isa     => 'Str',
    default => sub { 'Authorization' },
);


has 'auth_header_token_format' => (
    is      => 'rw',
    isa     => 'Str',
    default => sub { 'Token token=%s' },
);


has 'default_method' => (
    is      => 'rw',
    isa     => 'Str',
    default => sub { 'GET' },
);


has 'extension' => (
    is      => 'rw',
    isa     => 'Str',
    default => sub { '' },
);


has 'user_agent' => (
    is      => 'rw',
    isa     => 'Str',
    default => sub { __PACKAGE__ . ' ' . $Web::API::VERSION },
);


has 'timeout' => (
    is      => 'rw',
    isa     => 'Int',
    default => sub { 30 },
    lazy    => 1,
);


has 'strict_ssl' => (
    is      => 'rw',
    isa     => 'Bool',
    default => sub { 1 },
    lazy    => 1,
);


has 'agent' => (
    is       => 'rw',
    isa      => 'LWP::UserAgent',
    lazy     => 1,
    required => 1,
    builder  => '_build_agent',
);


has 'retry_http_codes' => (
    is  => 'rw',
    isa => 'ArrayRef[Int]',
);


has 'retry_errors' => (
    is  => 'rw',
    isa => 'ArrayRef[RegexpRef]',
);


has 'retry_times' => (
    is      => 'rw',
    isa     => 'Int',
    lazy    => 1,
    default => sub { 3 },
);


has 'retry_delay' => (
    is      => 'rw',
    isa     => 'Num',
    lazy    => 1,
    default => sub { 1.0 },
);


has 'content_type' => (
    is      => 'rw',
    isa     => 'Str',
    default => sub { 'text/plain' },
);


has 'incoming_content_type' => (
    is  => 'rw',
    isa => 'Str',
);


has 'outgoing_content_type' => (
    is  => 'rw',
    isa => 'Str',
);


has 'debug' => (
    is      => 'rw',
    isa     => 'Bool',
    default => sub { 0 },
    lazy    => 1,
);


has 'cookies' => (
    is      => 'rw',
    isa     => 'HTTP::Cookies',
    default => sub { HTTP::Cookies->new },
);


has 'consumer_secret' => (
    is  => 'rw',
    isa => 'Str',
);


has 'access_token' => (
    is  => 'rw',
    isa => 'Str',
);


has 'access_secret' => (
    is  => 'rw',
    isa => 'Str',
);


has 'signature_method' => (
    is      => 'rw',
    isa     => 'Str',
    default => sub { 'HMAC-SHA1' },
    lazy    => 1,
);


has 'encoder' => (
    is        => 'rw',
    isa       => 'CodeRef',
    predicate => 'has_encoder',
);


has 'decoder' => (
    is        => 'rw',
    isa       => 'CodeRef',
    predicate => 'has_decoder',
);


has 'oauth_post_body' => (
    is      => 'rw',
    isa     => 'Bool',
    default => sub { 1 },
    lazy    => 1,
);


has 'error_keys' => (
    is  => 'rw',
    isa => 'ArrayRef[Str]',
);

has 'base_url' => (
    is  => 'rw',
    isa => 'Str',
);

has 'json' => (
    is      => 'rw',
    isa     => 'JSON',
    default => sub {
        my $js = JSON->new;
        $js->utf8;
        $js->allow_blessed;
        $js->convert_blessed;
        $js->allow_nonref;
        $js;
    },
);

has 'xml' => (
    is      => 'rw',
    isa     => 'XML::Simple',
    lazy    => 1,
    default => sub {
        XML::Simple->new(
            ContentKey => '-content',
            NoAttr     => 1,
            KeepRoot   => 1,
            KeyAttr    => {},
        );
    },
);

has '_decoded_response' => (
    is      => 'rw',
    isa     => 'Ref',
    clearer => 'clear_decoded_response',
);

has '_response' => (
    is      => 'rw',
    isa     => 'HTTP::Response',
    clearer => 'clear_response',
);

sub _build_agent {
    my ($self) = @_;

    return LWP::UserAgent->new(
        agent      => $self->user_agent,
        cookie_jar => $self->cookies,
        timeout    => $self->timeout,
        keep_alive => 1,
        ssl_opts   => { verify_hostname => $self->strict_ssl },
    );
}

sub _build_live_test_url {
    my ($self) = @_;

    return $self->base_url if $self->base_url;
    return;
}


sub nonce {
    return join('', rand_chars(size => 16, set => 'alphanumeric'));
}


sub log {    ## no critic (ProhibitBuiltinHomonyms)
    my ($self, $msg) = @_;
    print STDERR caller() . ': '
        . ($self->test ? '[test] ' : '[LIVE] ')
        . $msg
        . $/;
    return;
}


sub decode {
    my ($self, $content, $content_type) = @_;

    $self->log("decoding response from '$content_type'") if $self->debug;

    my $data;
    eval {
        if ($self->has_decoder) {
            $self->log('running custom decoder') if $self->debug;
            $data = $self->decoder->($content, $content_type);
        }
        else {
            for ($content_type) {
                if (/urlencoded/) {
                    foreach (split(/&/, $content)) {
                        my ($key, $value) = split(/=/, $_);
                        $data->{ uri_unescape($key) } = uri_unescape($value);
                    }
                }
                elsif (/json/) { $data = $self->json->decode($content); }
                elsif (/(xml|html)/) {
                    $data = $self->xml->XMLin($content, NoAttr => 0);
                }
                else {
                    $data = { text => $content };
                }
            }
        }
    };

    die("couldn't decode payload using $content_type: $@\n" . np($content))
        if ($@ || ref \$content ne 'SCALAR');

    $self->_decoded_response($data);

    return $data;
}


sub encode {
    my ($self, $options, $content_type) = @_;

    $self->log("encoding response to '$content_type'") if $self->debug;

    my $payload;
    eval {
        # custom encoder should only be run if called by Web::API otherwise we
        # end up calling it twice
        if ($self->has_encoder and caller(1) eq 'Web::API') {
            $self->log('running custom encoder') if $self->debug;
            $payload = $self->encoder->($options, $content_type);
        }
        else {
            for ($content_type) {
                if (/urlencoded/) {
                    $payload .=
                        uri_escape($_) . '=' . uri_escape($options->{$_}) . '&'
                        foreach (keys %$options);
                    chop($payload);
                }
                elsif (/json/) { $payload = $self->json->encode($options); }
                elsif (/xml/)  { $payload = $self->xml->XMLout($options); }
                else {
                    if (exists $options->{payload}
                        and defined $options->{payload})
                    {
                        $payload = '' . $options->{payload};
                    }
                }
            }
        }
    };
    die("couldn't encode payload using $content_type: $@\n" . np(%$options))
        if ($@ || ref \$payload ne 'SCALAR');

    return $payload;
}


sub talk {
    my ($self, $command, $uri, $options, $query_keys, $content_type) = @_;

    my $method = uc($command->{method} || $self->default_method);
    my $oauth_req;

    # handle different auth_types
    for (lc $self->auth_type) {
        if ('basic') { $uri->userinfo($self->user . ':' . $self->api_key); }
        elsif ('header') {
            $self->header->{ $self->auth_header } =
                sprintf($self->auth_header_token_format, $self->api_key);
        }
        elsif ('hash_key') {
            my $api_key_field = $self->api_key_field;
            if ($self->mapping and not $command->{no_mapping}) {
                $self->log("mapping api_key_field: " . $self->api_key_field)
                    if $self->debug;
                $api_key_field = $self->mapping->{$api_key_field}
                    if $self->mapping->{$api_key_field};
            }
            $options->{$api_key_field} = $self->api_key;
        }
        elsif ('get_params') {
            $uri->query_form(
                $self->mapping->{user}    || 'user'    => $self->user,
                $self->mapping->{api_key} || 'api_key' => $self->api_key,
            );
        }
        elsif (/^oauth/) {
            my %opts = (
                consumer_key     => $self->api_key,
                consumer_secret  => $self->consumer_secret,
                request_url      => $uri,
                request_method   => $method,
                signature_method => $self->signature_method,
                timestamp        => time,
                nonce            => $self->nonce,
                token            => $self->access_token,
                token_secret     => $self->access_secret,
            );

            if (
                $options
                and (($self->oauth_post_body and $method eq 'POST')
                    or $method ne 'POST'))
            {
                $opts{extra_params} = { %$options, %{ $query_keys || {} } };
            }

            $oauth_req = Net::OAuth->request("protected resource")->new(%opts);
            $oauth_req->sign;
        }
        else {
            $self->log(
                "WARNING: auth_type " . $self->auth_type . " not supported yet")
                unless (lc($self->auth_type) eq 'none');
        }
    }

    # encode payload
    my $payload;
    if (keys %$options) {
        if ($method =~ m/^(GET|HEAD|DELETE)$/) {

            # TODO: check whether $option is a flat hashref

            unless ($self->auth_type eq 'oauth_params') {
                $uri->query_param_append($_ => $options->{$_})
                    for (keys %$options);
            }
        }
        else {
            $payload = $self->encode($options, $content_type->{out});
            $self->log("send payload: $payload") if $self->debug;
        }
    }

    # append query keys to URI
    $uri->query_param_append($_ => $query_keys->{$_}) for keys %$query_keys;

    $uri = $oauth_req->to_url if ($self->auth_type eq 'oauth_params');

    # build headers
    my %header = %{ $self->header };
    if (exists $command->{headers} and ref $command->{headers} eq 'HASH') {
        %header = (%header, %{ $command->{headers} });
    }
    my $headers = HTTP::Headers->new("Accept" => $content_type->{in}, %header);

    if ($self->debug) {
        $self->log("uri: $method $uri");
        $self->log("extra headers: " . np(%header)) if (%header);
        $self->log("OAuth headers: " . $oauth_req->to_authorization_header)
            if ($self->auth_type eq 'oauth_header');
    }

    # build request
    my $request = HTTP::Request->new($method, $uri, $headers);
    unless ($method =~ m/^(GET|HEAD|DELETE)$/) {
        $request->header("Content-type" => $content_type->{out});
        $request->content($payload);
    }

    # oauth POST
    if (    $options
        and ($method eq 'POST')
        and ($self->auth_type =~ m/^oauth/)
        and $self->oauth_post_body)
    {
        $request->content($oauth_req->to_post_body);
    }

    # oauth_header
    $request->header(Authorization => $oauth_req->to_authorization_header)
        if ($self->auth_type eq 'oauth_header');

    # add session cookies
    $self->agent->cookie_jar($self->cookies);

    # do the actual work
    return $self->request($request);
}


sub map_options {
    my ($self, $options, $command) = @_;

    my %opts;

    # first include default attributes
    %opts = %{ $command->{default_attributes} }
        if exists $command->{default_attributes};

    # then map everything in $options, overwriting default_attributes if necessary
    if ($self->mapping and not $command->{no_mapping}) {
        $self->log("mapping hash:\n" . np(%{ $self->mapping })) if $self->debug;

        # do the key and value mapping of options hash and overwrite defaults
        foreach my $key (keys %$options) {
            my ($newkey, $newvalue);
            $newkey = $self->mapping->{$key} if ($self->mapping->{$key});
            $newvalue = $self->mapping->{ $options->{$key} }
                if ($options->{$key} and $self->mapping->{ $options->{$key} });

            $opts{ $newkey || $key } = $newvalue || $options->{$key};
        }

        # and write everything back to $options
        $options = \%opts;
    }
    else {
        $options = { %opts, %$options };
    }

    return $options;
}


sub check_mandatory {
    my ($self, $options, $mandatory) = @_;

    $self->log("mandatory keys:\n" . np(@$mandatory))
        if $self->debug;

    my @missing_attrs;
    foreach my $attr (@$mandatory) {
        push(@missing_attrs, $attr)
            unless $self->key_exists($attr, $options);
    }

    die 'mandatory attributes for this command missing: '
        . join(', ', @missing_attrs)
        . $/
        if @missing_attrs;

    return;
}


sub key_exists {
    my ($self, $path, $hash) = @_;

    my @bits = split /\./, $path;
    my $node = $hash;

    return $node
        if @bits == grep {
               ref $node eq "HASH"
            && exists $node->{$_}
            && ($node = $node->{$_} // {})
        } @bits;

    return;
}


sub wrap {
    my ($options, $wrapper, $content_type) = @_;

    if (ref $wrapper eq 'ARRAY') {

        # XML needs wrapping into extra array ref layer to make XML::Simple
        # behave correctly
        if ($content_type =~ m/xml/) {
            $options = { $_ => [$options] } for (reverse @$wrapper);
        }
        else {
            $options = { $_ => $options } for (reverse @$wrapper);
        }
    }
    elsif (defined $wrapper) {
        $options = { $wrapper => $options };
    }

    return $options;
}


sub request {
    my ($self, $request) = @_;

    my $response;
    my $error;

    if (   ($self->retry_http_codes and scalar(@{ $self->retry_http_codes }))
        or ($self->retry_errors and scalar(@{ $self->retry_errors })))
    {
        my $times = $self->retry_times;
        my $n     = 0;

        while ($times-- > 0) {
            $n++;
            $self->log("try: $n/"
                    . $self->retry_times
                    . ' delay: '
                    . $self->retry_delay . 's')
                if $self->debug;

            $response = eval { $self->agent->request($request) };
            $error = $@;

            # if the user agent died there was a connection issue, definitely retry those
            unless ($error) {
                $self->_response($response);

                $self->log("recv payload: " . $response->decoded_content)
                    if $self->debug;

                return $response
                    unless $self->needs_retry($response,
                    $request->header('Accept'));
            }

            sleep $self->retry_delay if $times;    # Do not sleep in last time
        }
    }
    else {
        $response = eval { $self->agent->request($request) };
        $error = $@;

        $self->log("recv payload: " . $response->decoded_content)
            if $response and $self->debug;
    }

    $self->_response($response);

    die $error if $error;

    return $response;
}


sub needs_retry {
    my ($self, $response, $content_type) = @_;

    $self->log("response code was: " . $response->code)
        if $self->debug;

    if ($self->retry_http_codes) {
        for my $retry_http_code (@{$self->retry_http_codes}) {
            return 1 if $response->code == $retry_http_code;
        }
    }

    if (    $self->retry_errors
        and scalar(@{ $self->retry_errors })
        and $self->error_keys
        and scalar(@{ $self->error_keys }))
    {
        # we need to decode the response content to be able to find a custom
        # error field
        my $content = $self->decode($response->decoded_content,
            ($response->header('Content-Type') || $content_type));

        my $error = $self->find_error($content);

        return unless $error;

        return 1 if map { $error =~ $_ } @{ $self->retry_errors };
    }

    return;
}


sub find_error {
    my ($self, $content) = @_;

    for (@{ $self->error_keys || [] }) {
        $self->log("checking for error at ($_)") if $self->debug;

        my $node = $self->key_exists($_, $content);

        if ($node) {
            $self->log("found error: '$node' at ($_)") if $self->debug;
            return $node;
        }
    }

    return;
}


sub format_response {
    my ($self, $response, $ct, $error) = @_;

    my $answer;

    if ($response) {

        # collect response headers
        my $response_headers;
        $response_headers->{$_} = $response->header($_)
            foreach ($response->header_field_names);

        # decode content if necessary
        unless ($self->_decoded_response) {
            if (    defined $response->decoded_content
                and length($response->decoded_content) > 0
                and $response->decoded_content =~ m/\S/)
            {
                $self->_decoded_response(
                    eval {
                        $self->decode($response->decoded_content,
                            ($response_headers->{'Content-Type'} || $ct));
                    });
                $error ||= $@;
            }
        }

        # search for and expose errors
        $error ||= $self->find_error($self->_decoded_response);

        $answer = {
            header  => $response_headers,
            code    => $response->code,
            content => $self->_decoded_response,
            raw     => $response->content,
            cookies => $self->cookies->get_cookies($self->base_url),
        };

        unless ($response->is_success || $response->is_redirect) {
            $error ||= $response->status_line;
        }
    }

    if ($error) {
        chomp($error);
        $self->log("ERROR: $error") if $self->debug;
        $answer->{error} = $error;
    }

    return $answer;
}


sub build_uri {
    my ($self, $command, $options, $path) = @_;

    my $uri = URI->new($self->base_url);
    my $p   = $uri->path;

    if ($path) {
        $p .= '/' . $path;

        # parse all mandatory ID keys from URI path
        # format: /path/with/some/:id/and/:another_id/fun.js
        my @mandatory = ($path =~ m/:(\w+)/g);

        # and replace placeholders
        foreach my $key (@mandatory) {
            die "required {$key} option missing\n"
                unless (exists $options->{$key});

            my $encoded_option = uri_escape(delete $options->{$key});
            $p =~ s/:$key/$encoded_option/gex;
        }
    }
    else {
        $p .= "/$command";
    }

    $p .= '.' . $self->extension if ($self->extension);
    $uri->path($p);

    return $uri;
}


sub build_content_type {
    my ($self, $command) = @_;

    return {
        in => $command->{incoming_content_type}
            || $command->{content_type}
            || $CONTENT_TYPE{ $self->extension }
            || $self->incoming_content_type
            || $self->content_type,
        out => $command->{outgoing_content_type}
            || $command->{content_type}
            || $self->outgoing_content_type
            || $self->content_type,
    };
}


sub DESTROY { }


sub AUTOLOAD {
    my ($self, %options) = @_;

    $self->clear_decoded_response;
    $self->clear_response;

    $self->base_url($self->test ? $self->test_url : $self->live_url);

    # sanity checks
    die "Attribute (base_url) is required\n" unless $self->base_url;
    if ($self->auth_type =~ m/^oauth_/) {
        for (qw(consumer_secret access_token access_secret)) {
            die "Attribute ($_) is required\n" unless $self->$_;
        }
    }

    my ($command) = $AUTOLOAD =~ /([^:]+)$/;

    my $ct;
    my $response = eval {
        die "unknown command: $command\n"
            unless (exists $self->commands->{$command});

        my $options = \%options;

        # construct URI
        my $uri =
            $self->build_uri($command, $options,
            $self->commands->{$command}->{path});

        # first select the right content types for encoding/decoding
        $ct = $self->build_content_type($self->commands->{$command});

        # then map options if necessary
        $options =
            $self->map_options($options, $self->commands->{$command}, $ct->{in})
            if (((keys %$options) and ($ct->{out} =~ m/(xml|json|urlencoded)/))
            or (exists $self->commands->{$command}->{default_attributes})
            or (exists $self->commands->{$command}->{mandatory}));

        # then check existence of mandatory attributes
        $self->check_mandatory($options,
            $self->commands->{$command}->{mandatory})
            if exists $self->commands->{$command}->{mandatory};

        # then extract query keys from options to prevent them being wrapped
        # in the next step
        my $query_keys;
        foreach my $key (keys %$options) {
            my $command_query_keys = $self->commands->{$command}->{query_keys} || [];
            for my $command_query_key (@$command_query_keys) {
                $query_keys->{$key} = delete $options->{$key} if $key eq $command_query_key;
            }
        }

        # finally wrap all options in wrapper key(s) if requested
        my $method =
            uc($self->commands->{$command}->{method} || $self->default_method);
        $options =
            wrap($options,
            $self->commands->{$command}->{wrapper} || $self->wrapper,
            $ct->{in})
            unless ($method =~ m/^(GET|HEAD|DELETE)$/);

        $self->log("options:\n" . np(%$options)) if $self->debug;

        # do the talking
        return $self->talk($self->commands->{$command},
            $uri, $options, $query_keys, $ct);
    };

    return $self->format_response($self->_response, $ct->{in}, $@);
}


1;    # End of Web::API

__END__

=pod

=encoding UTF-8

=head1 NAME

Web::API - A Simple base module to implement almost every RESTful API with just a few lines of configuration

=head1 VERSION

version 2.8

=head1 SYNOPSIS

B<NOTE:> as of version 2.1 C<strict_ssl> is enabled by default for obvious security
reasons, this may break your current library implementation, sorry.

Implement the RESTful API of your choice in 10 minutes, roughly.

    package Net::CloudProvider;

    use Mouse;

    with 'Web::API';

    our $VERSION = "0.1";

    has 'commands' => (
        is      => 'rw',
        default => sub {
            {
                list_nodes => { method => 'GET' },
                node_info  => { method => 'GET', require_id => 1 },
                create_node => {
                    method             => 'POST',
                    default_attributes => {
                        allowed_hot_migrate            => 1,
                        required_virtual_machine_build => 1,
                        cpu_shares                     => 5,
                        required_ip_address_assignment => 1,
                        primary_network_id             => 1,
                        required_automatic_backup      => 0,
                        swap_disk_size                 => 1,
                    },
                    mandatory => [
                        'label',
                        'hostname',
                        'template_id',
                        'cpus',
                        'memory',
                        'primary_disk_size',
                        'required_virtual_machine_build',
                        'cpu_shares',
                        'primary_network_id',
                        'required_ip_address_assignment',
                        'required_automatic_backup',
                        'swap_disk_size',
                    ]
                },
                update_node => { method => 'PUT',    require_id => 1 },
                delete_node => { method => 'DELETE', require_id => 1 },
                start_node  => {
                    method       => 'POST',
                    require_id   => 1,
                    post_id_path => 'startup',
                },
                stop_node => {
                    method       => 'POST',
                    require_id   => 1,
                    post_id_path => 'shutdown',
                },
                suspend_node => {
                    method       => 'POST',
                    require_id   => 1,
                    post_id_path => 'suspend',
                },
            };
        },
    );

    sub commands {
        my ($self) = @_;
        return $self->commands;
    }

    sub BUILD {
        my ($self) = @_;

        $self->user_agent(__PACKAGE__ . ' ' . $VERSION);
        $self->live_url('https://ams01.cloudprovider.net/virtual_machines');
        $self->content_type('application/json');
        $self->extension('json');
        $self->wrapper('virtual_machine');
        $self->mapping({
                os        => 'template_id',
                debian    => 1,
                id        => 'label',
                disk_size => 'primary_disk_size',
        });

        return $self;
    }

    1;

later use as:

    use Net::CloudProvider;

    my $nc = Net::CloudProvider->new(user => 'foobar', api_key => 'secret');
    my $response = $nc->create_node({
        id                             => 'funnybox',
        hostname                       => 'node.funnybox.com',
        os                             => 'debian',
        cpus                           => 2,
        memory                         => 256,
        disk_size                      => 5,
        allowed_hot_migrate            => 1,
        required_virtual_machine_build => 1,
        cpu_shares                     => 5,
        required_ip_address_assignment => 1,
    });

=head1 ATTRIBUTES

=head2 commands

most important configuration part of the module which has to be provided by the
module you are writing.

the following keys are valid/possible:

    method
    path
    mandatory
    default_attributes
    headers
    extension
    content_type
    incoming_content_type
    outgoing_content_type
    wrapper
    query_keys
    require_id (deprecated, use path)
    pre_id_path (deprecated, use path)
    post_id_path (deprecated, use path)

the request path for commands is being build as:

    $base_url/$path.$extension

an example for C<path>:

    path => 'users/:user_id/labels'

this will add C<user_id> to the list of mandatory keys for this command
automatically.

=head2 live_url (required)

get/set base URL to API, can include paths

=head2 test_url (optional)

get/set base URL for test system if applicable

=head2 test (optional)

get/set boolean to run against base URL from test system or live system

=head2 api_key (required in most cases)

get/set API key (also used as basic auth password)

=head2 user (optional)

get/set API username/account name

=head2 api_key_field (optional)

get/set name of the hash key that has to hold the C<api_key>
e.g. in POST content payloads

=head2 api_version (optional)

get/set API version to be used

default: 1

=head2 mapping (optional)

supply mapping table, hashref of format { "key" => "value", ... }

=head2 wrapper (optional)

get/set name of the key that is used to wrap all options of a command in.
unfortunately some APIs increase the depth of a hash by wrapping everything into
a single key (who knows why...), which means this:

    $wa->command(%options);

turns C<%options> into:

    { wrapper => \%options }

before encoding and sending it off.

=head2 header (optional)

get/set custom headers sent with every request

=head2 auth_type

get/set authentication type. currently supported are only 'basic', 'header',
'hash_key', 'get_params', 'oauth_header', 'oauth_params' or 'none'

default: none

=head2 auth_header (optional)

get/set the name of the header used for Authorization credentials

default: Authorization

=head2 auth_header_token_format

get/set format of the auth_header token.

default: 'Token token=%s'

=head2 default_method (optional)

get/set default HTTP method

default: GET

=head2 extension (optional)

get/set file extension, e.g. 'json'

=head2 user_agent (optional)

get/set User Agent String

default: "Web::API $VERSION"

=head2 timeout (optional)

get/set L<LWP::UserAgent> timeout

=head2 strict_ssl (optional)

enable/disable strict SSL certificate hostname checking as a convenience
alternatively you can supply your own LWP::Useragent compatible agent for
the C<agent> attribute.

default: true

=head2 agent (optional)

get/set L<LWP::UserAgent> object

=head2 retry_http_codes (optional)

get/set array of HTTP response codes that trigger a retry of the request

=head2 retry_errors (optional)

define an array reference of regexes that should trigger a retry of the request
if matched against an error found via one of the C<error_keys>

=head2 retry_times (optional)

get/set number of times a request will be retried at most

default: 3

=head2 retry_delay (optional)

get/set delay to wait between retries. accepts float for millisecond support.

default: 1.0

=head2 content_type (optional)

global content type, which is used for in and out going request/response
headers and to encode and decode the payload if no other more specific content
types are set, e.g. C<incoming_content_type>, C<outgoing_content_type> or
content types set individually per command attribute.

default: 'text/plain'

=head2 incoming_content_type (optional)

default: undef

=head2 outgoing_content_type (optional)

default: undef

=head2 debug (optional)

enable/disabled debug logging

default: false

=head2 cookies (optional)

this is used to store and retrieve cookies before and after requests were made
to keep authenticated sessions alive for the time this object exists in memory
you can add your own cookies to be send with every request. See
L<HTTP::Cookies> for more information.

default: HTTP::Cookies->new()

=head2 consumer_secret (required for all oauth_* auth_types)

default: undef

=head2 access_token (required for all oauth_* auth_types)

default: undef

=head2 access_secret (required for all oauth_* auth_types)

default: undef

=head2 signature_method (required for all oauth_* auth_types)

default: undef

=head2 encoder (custom options encoding subroutine)

Receives C<\%options> and C<content-type> as the only 2 arguments and has to
return a single scalar.

default: undef

=head2 decoder (custom response content decoding subroutine)

Receives C<content> and C<content-type> as the only 2 scalar arguments and has
to return a single hash reference.

default: undef

=head2 oauth_post_body (required for all oauth_* auth_types)

enable/disable adding of command options as extra parameters to the OAuth
request generation and therefor be included in the OAuth signature calculation.

default: true

=head2 error_keys

get/set list of array keys that will be search for in the decoded response data
structure. the same format as for mandatory keys is supported:

    some.deeply.nested.error.message

will search for an error message at

    $decoded_response->{some}->{deeply}->{nested}->{error}->{messsage}

and if the key exists and its value is defined it will be provided as
C<$response->{error}> and matched against all regexes from the `retry_errors`
array ref if provided to trigger a retry on particular errors.

=head1 INTERNAL SUBROUTINES/METHODS

=head2 nonce

generates new OAuth nonce for every request

=head2 log

=head2 decode

=head2 encode

=head2 talk

=head2 map_options

=head2 check_mandatory

=head2 key_exists

=head2 wrap

=head2 request

retry request with delay if C<retry_http_codes> is set, otherwise just try once.

=head2 needs_retry

returns true if the HTTP code or error found match either C<retry_http_codes>
or C<retry_errors> respectively.
returns false otherwise.

if C<retry_errors> are defined it will try to decode the response content and
store the decoded structure internally so we don't have to decode again at the
end.

needs the last response object and the 'Accept' content type header from the
request for decoding.

=head2 find_error

go through C<error_keys> and find a potential error message in the decoded/parsed
response and return it.

=head2 format_response

=head2 build_uri

=head2 build_content_type

configure in/out content types

order of precedence:
1. per command C<incoming_content_type> / C<outgoing_content_type>
2. per command general C<content_type>
3. content type based on file path extension (only for incoming)
4. global C<incoming_content_type> / C<outgoing_content_type>
5. global general C<content_type>

=head2 DESTROY

catch DESTROY call and tear down / clean up if necessary
at this point there is nothing to do though. This prevents
AUTOLOAD from logging an unknown command error message

=head2 AUTOLOAD magic

install a method for each new command and call it in an C<eval {}> to catch
exceptions and set an error in a unified way.

=head1 BUGS

Please report any bugs or feature requests on GitHub's issue tracker L<https://github.com/nupfel/Web-API/issues>.
Pull requests welcome.

=head1 SUPPORT

You can find documentation for this module with the L<perldoc(1)> command.

    perldoc Web::API

You can also look for information at:

=over 4

=item * GitHub repository

L<https://github.com/nupfel/Web-API>

=item * MetaCPAN

L<https://metacpan.org/module/Web::API>

=item * AnnoCPAN: Annotated CPAN documentation

L<http://annocpan.org/dist/Web::API>

=item * CPAN Ratings

L<http://cpanratings.perl.org/d/Web::API>

=back

=head1 SEE ALSO

L<HTTP::Cookies>, L<LWP::UserAgent>, L<Net::OAuth>

=head1 AUTHOR

Tobias Kirschstein <lev@cpan.org>

=head1 COPYRIGHT AND LICENSE

This software is Copyright (c) 2013 by Tobias Kirschstein.

This is free software, licensed under:

  The (three-clause) BSD License

=cut