From 2b4aa10ef47b50f19267bf3155df7bbfe4c3dbdb Mon Sep 17 00:00:00 2001
From: "flyingscorpio@arch-desktop" <tfranken@protonmail.com>
Date: Tue, 5 May 2020 18:13:23 +0200
Subject: [PATCH] Do corona script in Python

---
 dotfiles/i3/blocks         |   2 +-
 dotfiles/i3/scripts/corona | 143 +++++++++++++++++++++++++++++++++----
 2 files changed, 129 insertions(+), 16 deletions(-)

diff --git a/dotfiles/i3/blocks b/dotfiles/i3/blocks
index 712359f..56564b7 100644
--- a/dotfiles/i3/blocks
+++ b/dotfiles/i3/blocks
@@ -59,7 +59,7 @@ LABEL=<span foreground='#a1d569'>  </span>
 DISK=/run/media/flyingscorpio/Backup
 
 [corona]
-interval=86400
+interval=5
 
 [ccurrency]
 command=scripts/ccurrency -f USD
diff --git a/dotfiles/i3/scripts/corona b/dotfiles/i3/scripts/corona
index f26fc2f..e5803c3 100755
--- a/dotfiles/i3/scripts/corona
+++ b/dotfiles/i3/scripts/corona
@@ -1,18 +1,131 @@
-#!/bin/sh
+#!/usr/bin/env python3
 
-[ "$(stat -c %y ~/.cache/corona 2>/dev/null | cut -d' ' -f1)" != "$(date '+%Y-%m-%d')" ] &&
-    curl -s 'https://corona-stats.online/France?source=1&minimal=true&emojis=true' > ~/.cache/corona
+"""Parse json from corona-stats to display in i3blocks.
+
+Author: flyingscorpio
+"""
+
+from datetime import datetime
+import json
+import os
+from pathlib import Path
+import subprocess
+from typing import Any, Dict, List
 
 
-grep "France" ~/.cache/corona |
-    sed "s/\[31m//g" |
-    sed "s/\[32m//g" |
-    sed "s/\[33m//g" |
-    sed "s/\[39m//g" |
-    sed "s/\[90m//g" |
-    sed "s/\[91m//g" |
-    sed "s/\[94m//g" |
-    sed "s/\[97m//g" |
-    sed "s/\s*//g" |
-    sed "s/\^\[/;/g" |
-    awk -F';' '{print $1}'
+def grab_json_with_curl() -> str:
+    """Run the curl command in a shell and grab the output as json."""
+
+    curl_cmd = subprocess.run(
+        "curl -s 'https://corona-stats.online/France?source=1&format=json'",
+        capture_output=True,
+        check=True,
+        shell=True,
+    )
+
+    return curl_cmd.stdout.decode()
+
+
+def write_curl_to_file(data: str, path: Path) -> None:
+    """Write the data from the curl command to a file."""
+
+    with open(path, "w") as corona_file:
+        corona_file.write(data)
+
+
+def read_json_from_file(path: Path) -> List[Dict[str, Any]]:
+    """Read from the corona file and return a list given by json format."""
+
+    with open(path, "r") as corona_file:
+        content = corona_file.read()
+
+    data: List[Dict[str, Any]] = json.loads(content)
+
+    return data
+
+
+def select_dict_by_province(data: List[Dict[str, Any]],
+                            province: str = "Global") -> Dict[str, Any]:
+    """Given the main data list from json, return the dict to work on based on
+    the province.
+    """
+
+    if province == "Global":
+        province = ""
+
+    for item in data:
+        if item['province'] == province:
+            return item
+
+    raise KeyError(f"{province} wasn't found in the data")
+
+
+def print_to_output(confirmed: int, today_confirmed_int: int,
+                    deaths: int, today_deaths_int: int) -> None:
+    """Format the data for the i3block."""
+
+    if today_confirmed_int >= 0:
+        today_confirmed = f"+{today_confirmed_int}"
+    else:
+        today_confirmed = f"{today_confirmed_int}"
+
+    if today_deaths_int >= 0:
+        today_deaths = f"+{today_deaths_int}"
+    else:
+        today_deaths = f"{today_deaths_int}"
+
+    output = f"{confirmed} ({today_confirmed})  ✝ {deaths} ({today_deaths})"
+
+    print(output)
+
+
+def generate_graph(data: List[int]) -> None:
+    """Generate a small graph based on the evolution of numbers in the list."""
+
+    print("HELLO THERE")
+
+
+def main() -> None:
+    """Grab the data, select the region, split the values."""
+
+    corona_file = Path("~/.cache/corona").expanduser()
+
+    stat_cmd = subprocess.run(
+        f"stat -c %y {corona_file} | cut -d' ' -f1",
+        capture_output=True,
+        check=False,
+        shell=True,
+    )
+    stat_date = stat_cmd.stdout.decode().strip()
+
+    current_date = datetime.now()
+    today = f"{current_date.year}-{current_date.month:02d}-{current_date.day:02d}"
+
+    if stat_date == today:
+        data = read_json_from_file(corona_file)
+    else:
+        curl_data = grab_json_with_curl()
+        write_curl_to_file(curl_data, corona_file)
+
+    data = read_json_from_file(corona_file)
+
+    data_dict = select_dict_by_province(data)
+
+    confirmed = data_dict["confirmed"]
+    today_confirmed = data_dict["confirmedByDay"][-1] - data_dict["confirmedByDay"][-2]
+    deaths = data_dict["deaths"]
+    today_deaths = data_dict["deathsByDay"][-1] - data_dict["deathsByDay"][-2]
+
+    try:
+        if os.environ["BLOCK_BUTTON"] == "1":
+            generate_graph(data_dict["confirmedByDay"])
+        elif os.environ["BLOCK_BUTTON"] == "3":
+            generate_graph(data_dict["deathsByDay"])
+        else:
+            raise KeyError
+    except KeyError:
+        print_to_output(confirmed, today_confirmed, deaths, today_deaths)
+
+
+if __name__ == "__main__":
+    main()