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