about summary refs log tree commit diff stats
path: root/ara.pl
blob: a351eb6161a714b7de416eb4caa6086abc3f3fb1 (plain) (blame)
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
#!/usr/bin/perl

use strict;
use warnings;

use Path::Tiny;
use Time::Moment;
use Text::ASCIITable;
use Getopt::Long qw( GetOptions );
use JSON::MaybeXS qw( decode_json );

use OpenBSD::Unveil;

# Unveil @INC.
foreach my $path (@INC) {
    unveil( $path, 'rx' )
        or die "Unable to unveil: $!";
}

my ( $use_local_file, $get_latest, $state_notes, $rows_to_print );

GetOptions(
    "local" => \$use_local_file,
    "latest" => \$get_latest,
    "notes" => \$state_notes,
    "rows=i" => \$rows_to_print,
    "help" => sub { HelpMessage() },
) or die "Error in command line arguments";

sub HelpMessage {
    print "Options:
    --local  Use local data
    --latest Fetch latest data
    --notes  Print State Notes
    --rows=i Number of rows to print (i is Integer)
    --help   Print this help message
";
    exit;
}

die "Can't use --local and --latest together\n"
    if $use_local_file and $get_latest ;

# %unveil contains list of paths to unveil with their permissions.
my %unveil = (
    "/usr" => "rx",
    "/var" => "rx",
    "/etc" => "rx",
    "/dev" => "rx",
    "/tmp" => "rwc",
    "/dev/null" => "rw",
);

# Unveil each path from %unveil.
keys %unveil;

# We use sort because otherwise keys is random order everytime.
foreach my $path ( sort keys %unveil ) {
    unveil( $path, $unveil{$path} )
        or die "Unable to unveil: $!";
}

my $file = '/tmp/data.json';
my $file_mtime;

# If $file exists then get mtime.
if ( -e $file ) {
    my $file_stat = path($file)->stat;
    $file_mtime = Time::Moment->from_epoch( $file_stat->[9] );
} else {
    warn "File '$file' doesn't exist\nFetching latest...\n"
        if $use_local_file;
}

# Fetch latest data only if the local data is older than 8 minutes or
# if the file doesn't exist.
if ( not -e $file
         or $file_mtime < Time::Moment->now_utc->minus_minutes(8)
         or $get_latest ) {
    require HTTP::Tiny;

    # Fetch latest data from api.
    my $url = 'https://api.covid19india.org/data.json';

    my $response = HTTP::Tiny
        ->new( verify_SSL => 1 )
        ->mirror($url, $file);

    die "Failed to fetch latest data...
Reason: $response->{reason}\n
Content: $response->{content}
Status: $response->{status}\n"
        unless $response->{success};
}

# Slurp api response to $file_data.
my $file_data = path($file)->slurp;

# Block further unveil calls.
unveil()
    or die "Unable to lock unveil: $!";

# Decode $file_data to $json_data.
my $json_data = decode_json($file_data);

# Get statewise information.
my $statewise = $json_data->{statewise};

my ( $covid_19_data, $notes_table, @months, $today );

if ( $state_notes ) {
    $notes_table = Text::ASCIITable->new( { drawRowLine => 1 } );
    $notes_table->setCols( qw( State Notes ) );
    $notes_table->setColWidth( 'Notes', 74 );
} else {
    # Map month number to Months.
    @months = qw( lol Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec );

    $covid_19_data = Text::ASCIITable->new();
    $covid_19_data->setCols(
        'State',
        'Confirmed',
        'Active',
        'Recovered',
        'Deaths',
        'Last Updated',
    );

    $covid_19_data->alignCol( {
        'Confirmed' => 'left',
        'Recovered' => 'left',
        'Deaths' => 'left',
    } );

    $today = Time::Moment
        ->now_utc
        ->plus_hours(5)
        ->plus_minutes(30); # Current time in 'Asia/Kolkata' TimeZone.
}

# Print all the rows if $rows_to_print evaluates to False or is
# greater than the size of @$statewise or if user wants $state_notes.
$rows_to_print = scalar @$statewise
    if ( not $rows_to_print
             or $rows_to_print > scalar @$statewise
             or $state_notes );

foreach my $i ( 0 ... $rows_to_print - 1  ) {
    my $state = $statewise->[$i]{state};
    $state = "India"
        if $state eq "Total";

    $state = $statewise->[$i]{statecode}
        if length($state) > 16;

    if ( $state_notes ) {
        $notes_table->addRow(
            $state,
            $statewise->[$i]{statenotes},
        ) unless length($statewise->[$i]{statenotes}) == 0;
    } else {
        my $update_info;
        my $lastupdatedtime = $statewise->[$i]{lastupdatedtime};
        my $last_update_dmy = substr( $lastupdatedtime, 0, 10 );

        # Add $update_info.
        if ( $last_update_dmy
                 eq $today->strftime( "%d/%m/%Y" ) ) {
            $update_info = "Today";
        } elsif ( $last_update_dmy
                      eq $today->minus_days(1)->strftime( "%d/%m/%Y" ) ) {
            $update_info = "Yesterday";
        } elsif ( $last_update_dmy
                      eq $today->plus_days(1)->strftime( "%d/%m/%Y" ) ) {
            $update_info = "Tomorrow"; # Hopefully we don't see this.
        } else {
            $update_info =
                $months[substr( $lastupdatedtime, 3, 2 )] .
                " " .
                substr( $lastupdatedtime, 0, 2 );
        }

        my $confirmed = "$statewise->[$i]{confirmed}";
        my $recovered = "$statewise->[$i]{recovered}";
        my $deaths = "$statewise->[$i]{deaths}";

        # Add delta only if it was updated Today.
        if ( $update_info eq "Today" ) {
            if ( $statewise->[$i]{deltaconfirmed} >= 0 ) {
                $confirmed .= " (+$statewise->[$i]{deltaconfirmed})";
            } else {
                $confirmed .= " ($statewise->[$i]{deltaconfirmed})";
            }

            $recovered .= " (+$statewise->[$i]{deltarecovered})";
            $deaths .= " (+$statewise->[$i]{deltadeaths})";
        }

        $covid_19_data->addRow(
            $state,
            $confirmed,
            $statewise->[$i]{active},
            $recovered,
            $deaths,
            $update_info,
        );
    }
}

# Generate tables.
if ( $state_notes ) {
    print $notes_table;
} else {
    print $covid_19_data;
}