|
| 1 | +import logging |
| 2 | +import hashlib |
| 3 | +import subprocess |
| 4 | +import json |
| 5 | +import requests |
| 6 | +from pathlib import Path |
| 7 | +from typing import Tuple |
| 8 | +from functools import lru_cache |
| 9 | + |
| 10 | +from PySide6.QtWidgets import QDialog, QDialogButtonBox, QPlainTextEdit, QVBoxLayout, QLabel, QPushButton, QSizePolicy |
| 11 | +from PySide6.QtGui import QFont |
| 12 | +import pygments |
| 13 | +from pygments.lexers import JsonLexer |
| 14 | +from pygments.formatters import HtmlFormatter |
| 15 | + |
| 16 | +from platform_check import get_platform, PlatformEnum |
| 17 | +from gui_state import LogicState |
| 18 | + |
| 19 | +log = logging.getLogger('') |
| 20 | + |
| 21 | + |
| 22 | +class AnonStatsDialog(QDialog): |
| 23 | + def __init__(self, logic_state: LogicState, parent=None): |
| 24 | + super().__init__(parent) |
| 25 | + |
| 26 | + self.setWindowTitle('What statistics will be uploaded?') |
| 27 | + |
| 28 | + QBtn = QDialogButtonBox.Ok |
| 29 | + |
| 30 | + self.buttonBox = QDialogButtonBox(QBtn) |
| 31 | + self.buttonBox.accepted.connect(self.accept) |
| 32 | + |
| 33 | + usage_stats_html = dict_to_html(create_anon_stats(logic_state)) |
| 34 | + |
| 35 | + wLbl_1 = QLabel(''' |
| 36 | +These statistics are invaluable for us developers on figuring out what our users are actually |
| 37 | +building, so we can figure out where to put our (limited!) time working towards improving. |
| 38 | +After a successful OAT firmware upload the following data will be sent to our statistics server: |
| 39 | +'''.replace('\n', ' ')) |
| 40 | + wLbl_1.setWordWrap(True) |
| 41 | + wLbl_1.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) |
| 42 | + |
| 43 | + self.wBtn_show_hide = QPushButton('▶Click to expand:') |
| 44 | + self.wBtn_show_hide.setStyleSheet('QPushButton { color: #0074cc; background-color: transparent; border: 0px; }') |
| 45 | + self.wBtn_show_hide.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) |
| 46 | + self.wBtn_show_hide.clicked.connect(self.show_hide_html) |
| 47 | + |
| 48 | + self.wTxt_html = QPlainTextEdit() |
| 49 | + self.wTxt_html.setReadOnly(True) |
| 50 | + self.wTxt_html.appendHtml(f'{usage_stats_html}') |
| 51 | + self.wTxt_html.setMinimumSize(500, 250) |
| 52 | + self.wTxt_html.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) |
| 53 | + self.wTxt_html.hide() |
| 54 | + |
| 55 | + wLbl_2 = QLabel(''' |
| 56 | +(the data might not fully be populated yet, you need to progress through the GUI steps first) |
| 57 | +'''.replace('\n', ' ')) |
| 58 | + italic_font = QFont() |
| 59 | + italic_font.setItalic(True) |
| 60 | + wLbl_2.setFont(italic_font) |
| 61 | + wLbl_2.setWordWrap(True) |
| 62 | + wLbl_2.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) |
| 63 | + |
| 64 | + self.layout = QVBoxLayout() |
| 65 | + self.layout.addWidget(wLbl_1) |
| 66 | + self.layout.addWidget(self.wBtn_show_hide) |
| 67 | + self.layout.addWidget(self.wTxt_html) |
| 68 | + self.layout.addWidget(wLbl_2) |
| 69 | + self.layout.addWidget(self.buttonBox) |
| 70 | + self.setLayout(self.layout) |
| 71 | + |
| 72 | + def show_hide_html(self): |
| 73 | + show_hide_text = self.wBtn_show_hide.text() |
| 74 | + if self.wTxt_html.isVisible(): |
| 75 | + self.wTxt_html.hide() |
| 76 | + show_hide_text = show_hide_text.replace('▼', '▶') |
| 77 | + else: |
| 78 | + self.wTxt_html.show() |
| 79 | + show_hide_text = show_hide_text.replace('▶', '▼') |
| 80 | + self.wBtn_show_hide.setText(show_hide_text) |
| 81 | + |
| 82 | + |
| 83 | +def dict_to_html(in_dict: dict) -> str: |
| 84 | + json_str = json.dumps(in_dict, indent=4, sort_keys=True) |
| 85 | + json_lexer = JsonLexer() |
| 86 | + html_formatter = HtmlFormatter(noclasses=True, nobackground=True) |
| 87 | + data_html = pygments.highlight(json_str, json_lexer, html_formatter) |
| 88 | + return data_html |
| 89 | + |
| 90 | + |
| 91 | +def create_anon_stats(logic_state: LogicState) -> dict: |
| 92 | + if logic_state.release_idx is not None: |
| 93 | + release_name = logic_state.release_list[logic_state.release_idx].nice_name |
| 94 | + else: |
| 95 | + release_name = None |
| 96 | + |
| 97 | + if logic_state.config_file_path is not None: |
| 98 | + with open(Path(logic_state.config_file_path).resolve(), 'r') as fp: |
| 99 | + config_file = fp.read() |
| 100 | + else: |
| 101 | + config_file = None |
| 102 | + |
| 103 | + # Catch-all for these so we never crash when getting anon-stats |
| 104 | + try: |
| 105 | + computer_uuid = get_computer_uuid() |
| 106 | + except Exception as e: |
| 107 | + log.error(f'get_uuid exception: {e}') |
| 108 | + computer_uuid = 'unknown' |
| 109 | + try: |
| 110 | + approx_lat, approx_lon = get_approx_location() |
| 111 | + except Exception as e: |
| 112 | + log.error(f'get_approx_location exception: {e}') |
| 113 | + approx_lat, approx_lon = None, None |
| 114 | + |
| 115 | + stats = { |
| 116 | + 'host_uuid': computer_uuid, |
| 117 | + 'pio_env': logic_state.pio_env, |
| 118 | + 'release_version': release_name, |
| 119 | + 'config_file': config_file, |
| 120 | + 'approx_lat': approx_lat, |
| 121 | + 'approx_lon': approx_lon, |
| 122 | + } |
| 123 | + return stats |
| 124 | + |
| 125 | + |
| 126 | +def upload_anon_stats(anon_stats: dict) -> bool: |
| 127 | + analytics_url = 'http://config.cloud.openastrotech.com/api/v1/config/' |
| 128 | + log.info(f'Uploading statistics to {analytics_url}') |
| 129 | + try: |
| 130 | + r = requests.post(analytics_url, json=anon_stats, timeout=2.0) |
| 131 | + except Exception as e: |
| 132 | + log.error(f'Failed to POST statistics: {e}') |
| 133 | + return False |
| 134 | + if r.status_code != requests.codes.ok: |
| 135 | + log.error(f'Failed to POST statistics: {r.status_code} {r.reason} {r.text}') |
| 136 | + return False |
| 137 | + return True |
| 138 | + |
| 139 | + |
| 140 | +@lru_cache(maxsize=1) |
| 141 | +def get_computer_uuid() -> str: |
| 142 | + machine_id_fn = { |
| 143 | + PlatformEnum.WINDOWS: get_uuid_windows, |
| 144 | + PlatformEnum.LINUX: get_uuid_linux, |
| 145 | + PlatformEnum.UNKNOWN: lambda: 'unknown platform', |
| 146 | + }.get(get_platform(), lambda: 'unknown, unhandled platform') |
| 147 | + machine_id_str = machine_id_fn() |
| 148 | + |
| 149 | + if 'unknown' in machine_id_str.lower(): |
| 150 | + uuid_str = machine_id_str # Keep as human-readable, don't hash |
| 151 | + else: |
| 152 | + uuid_str = hashlib.sha256(machine_id_str.encode()).hexdigest() |
| 153 | + log.debug(f'Got UUID {repr(uuid_str)}') |
| 154 | + return uuid_str |
| 155 | + |
| 156 | + |
| 157 | +def get_uuid_windows() -> str: |
| 158 | + sub_proc = subprocess.run( |
| 159 | + ['powershell', |
| 160 | + '-Command', |
| 161 | + '(Get-CimInstance -Class Win32_ComputerSystemProduct).UUID', |
| 162 | + ], |
| 163 | + capture_output=True) |
| 164 | + if sub_proc.returncode != 0: |
| 165 | + return 'unknown-windows' |
| 166 | + windows_uuid = sub_proc.stdout.decode('UTF-8') |
| 167 | + return windows_uuid |
| 168 | + |
| 169 | + |
| 170 | +def get_uuid_linux() -> str: |
| 171 | + id_file = Path('/etc/machine-id') |
| 172 | + if not id_file.exists(): |
| 173 | + return 'unknown-linux' |
| 174 | + |
| 175 | + with open(id_file, 'r') as f: |
| 176 | + machine_id_contents = f.read().strip() |
| 177 | + return machine_id_contents |
| 178 | + |
| 179 | + |
| 180 | +def to_nearest_half(num: float) -> float: |
| 181 | + return round(num * 2, 0) / 2 |
| 182 | + |
| 183 | + |
| 184 | +@lru_cache(maxsize=1) |
| 185 | +def get_approx_location() -> Tuple[float, float]: |
| 186 | + geo_ip_url = 'https://ipinfo.io/loc' |
| 187 | + response = requests.get(geo_ip_url, timeout=2.0) |
| 188 | + resp_str = response.content.decode().strip() |
| 189 | + lat_str, lon_str = resp_str.split(',') |
| 190 | + lat_approx = to_nearest_half(float(lat_str)) |
| 191 | + lon_approx = to_nearest_half(float(lon_str)) |
| 192 | + return lat_approx, lon_approx |
0 commit comments