move oauth configuration into untracked include
[sc2-widget] / getsc2clan
1 #!/usr/bin/env perl
2 use 5.024;
3 use warnings;
4 use utf8;
5
6 use Data::Dump qw( pp );
7 use LWP::Authen::OAuth2;
8 use JSON qw( decode_json );
9 use List::Util qw( all );
10
11 my ($profileid, $clanmatch) = @ARGV;  # clan host and name
12 $profileid and $profileid =~ /\A\d+\z/
13         or die "Usage: $0 <profile id> [<clan name>]\n";
14
15 my %auth = do './.blizzard.passwd.pl' or die "no auth setup: $!\n";
16 my $bliz = LWP::Authen::OAuth2->new(%auth,
17         token_endpoint          => 'https://us.battle.net/oauth/token',
18         request_required_params => [qw( client_id client_secret grant_type )],
19 );
20 $bliz->request_tokens(grant_type => 'client_credentials');
21
22 sub blizget {
23         my $args = join('/', @_);
24         my $res = $bliz->get("https://us.api.blizzard.com/sc2/$args");
25         $res->is_success or die $res->status_line;
26         my $json = $res->decoded_content;
27         return decode_json($json);
28 }
29
30 # find largest group consisting entirely of clan members
31 # prefer deprecated interface to prevent costly ladder search
32 my $ladderdata = blizget(legacy => profile => 2 => 1 => $profileid => 'ladders');
33 my @ladders = (
34         sort {
35                 $b->{ladder}->[0]->{wins}+$b->{ladder}->[0]->{losses} <=>
36                 $a->{ladder}->[0]->{wins}+$a->{ladder}->[0]->{losses}
37         } # activity desc
38         grep {
39                 !$clanmatch or
40                 all { fc $_->{clanName} eq fc $clanmatch } $_->{characters}->@*
41         } # members
42         grep { $_->{ladder}->[0]->{division} }
43         $ladderdata->{currentSeason}->@*
44 ) or die "No matching groups found\n";
45 my (@members, %memberidx);
46 $memberidx{ $_->{id} } //= push(@members, $_) && $#members
47         for map { $_->{characters}->@* } @ladders;
48
49 say JSON->new->canonical->pretty->encode({
50         name     => $members[0]->{clanName},
51         tag      => $members[0]->{clanTag},
52         ladders  => [map {{
53                 league   => lc $_->{ladder}->[0]->{league},
54                 division => $_->{ladder}->[0]->{ladderName},
55                 rank     => $_->{ladder}->[0]->{rank},
56                 members  => [map { $memberidx{$_->{id}} } $_->{characters}->@*],
57                 wins     => $_->{ladder}->[0]->{wins},
58                 losses   => $_->{ladder}->[0]->{losses},
59         }} @ladders],
60         members  => [map {
61                 blizget(metadata => profile => 2 => 1 => $_->{id})
62                 # lacks mmr, fav race (available in new api)
63         } @members],
64 }) =~ s/(?: \G \d,? | \[ ) \K \s+ (?=\d|\])/ /grx; # concat arrays of single digits