#!/usr/bin/env python3 """ROB RUN free compatibility scan for macOS and Windows. Python 3.9+, no packages.""" import argparse import ctypes import json import locale import os from pathlib import Path import platform import re import secrets import shutil import subprocess import sys import tempfile import time from urllib.error import HTTPError, URLError from urllib.request import HTTPRedirectHandler, Request, build_opener import webbrowser SITE = "https://robrun.lol" USER_AGENT = "ROB-RUN-PC-Check/1.3 (Python)" WINDOWS_PROBE = r""" [Console]::OutputEncoding = [Text.UTF8Encoding]::new($false) $os = Get-CimInstance Win32_OperatingSystem $processors = @(Get-CimInstance Win32_Processor) $computer = Get-CimInstance Win32_ComputerSystem $gpu = @(Get-CimInstance Win32_VideoController | ForEach-Object {$_.Name}) $ram = (Get-CimInstance Win32_PhysicalMemory | Measure-Object Capacity -Sum).Sum $disks = @(Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3" | ForEach-Object { if ($null -ne $_.FreeSpace) { @{Name=$_.DeviceID; FreeGB=$_.FreeSpace / 1e9} } }) @{ Locale = (Get-UICulture).Name WindowsMajor = ([version]$os.Version).Major WindowsClient = ($os.ProductType -eq 1) NativeX64 = ($processors[0].Architecture -eq 9) Desktop = ($computer.PCSystemType -in 1,3) OS = $os.Caption Arch = $os.OSArchitecture CPU = (($processors | ForEach-Object {$_.Name}) -join ', ') GPU = ($gpu -join ', ') RamGB = ($ram / 1GB) Disks = $disks } | ConvertTo-Json -Depth 4 -Compress """ def probe(*args): try: result = subprocess.run( args, check=True, capture_output=True, text=True, encoding="utf-8-sig", errors="replace", timeout=45, ) return result.stdout.strip() except (OSError, subprocess.SubprocessError): return "" def clean(value): return " ".join(str(value or "").split())[:512] def mac_scan(): version = probe("/usr/bin/sw_vers", "-productVersion") memory = probe("/usr/sbin/sysctl", "-n", "hw.memsize") gpu_data = probe("/usr/sbin/system_profiler", "SPDisplaysDataType", "-json") try: displays = json.loads(gpu_data).get("SPDisplaysDataType", []) except json.JSONDecodeError: displays = [] gpu = ", ".join( clean(display.get("sppci_model") or display.get("_name")) for display in displays if display.get("sppci_model") or display.get("_name") ) languages = probe("/usr/bin/defaults", "read", "-g", "AppleLanguages") first_language = languages.lstrip("( \n\t").split(",", 1)[0].strip('" \n\t)') arm = probe("/usr/sbin/sysctl", "-n", "hw.optional.arm64") == "1" hardware = { "Platform": "Mac", "OS": "macOS " + version if version else "", "Arch": "arm64" if arm else platform.machine(), "CPU": clean(probe("/usr/sbin/sysctl", "-n", "machdep.cpu.brand_string")), "GPU": clean(gpu), "RamGB": int(memory) / 2**30 if memory.isdigit() else 0, "DirectX": "", "Disks": [{"Name": "Mac", "FreeGB": shutil.disk_usage("/").free / 1e9}], } return hardware, first_language def directx_feature_level(system32): # The runtime version alone does not prove that the hardware supports level 11_0. try: create = ctypes.WinDLL(str(system32 / "d3d11.dll")).D3D11CreateDevice uint, pointer = ctypes.c_uint32, ctypes.c_void_p create.argtypes = [pointer, uint, pointer, uint, ctypes.POINTER(uint), uint, uint, pointer, ctypes.POINTER(uint), pointer] create.restype = ctypes.c_int32 requested, supported = uint(0xB000), uint() result = create(None, 1, None, 0, ctypes.byref(requested), 1, 7, None, ctypes.byref(supported), None) if result >= 0 and supported.value >= requested.value: return "11.0+" except (OSError, AttributeError): pass return "" def windows_scan(): system32 = Path(os.environ.get("SystemRoot", r"C:\Windows")) / "System32" powershell = system32 / "WindowsPowerShell" / "v1.0" / "powershell.exe" data = probe(str(powershell), "-NoLogo", "-NoProfile", "-NonInteractive", "-Command", WINDOWS_PROBE) try: details = json.loads(data) hardware = { "Platform": "Windows", "OS": clean(details["OS"]), "Arch": clean(details["Arch"]), "CPU": clean(details["CPU"]), "GPU": clean(details["GPU"]), "RamGB": float(details["RamGB"] or 0), "DirectX": directx_feature_level(system32), "Disks": [ {"Name": disk["Name"], "FreeGB": float(disk["FreeGB"])} for disk in details.get("Disks", []) if re.fullmatch(r"[A-Za-z]:", str(disk.get("Name", ""))) and disk.get("FreeGB") is not None ], "WindowsMajor": int(details["WindowsMajor"]), "WindowsClient": details["WindowsClient"] is True, "NativeX64": details["NativeX64"] is True, "Desktop": details["Desktop"] is True, } except (ValueError, KeyError, TypeError, AttributeError) as error: raise RuntimeError("Could not read Windows hardware / 无法读取 Windows 硬件") from error return hardware, clean(details.get("Locale")) def serialize_scan(hardware): scan_id = secrets.token_urlsafe(32) body = json.dumps( {"scanId": scan_id, "hardware": hardware}, ensure_ascii=False, allow_nan=False, separators=(",", ":"), ).encode("utf-8") return scan_id, body def save_scan(body, os_name): if os_name == "Darwin": cache = Path.home() / "Library" / "Caches" else: cache = Path(os.environ.get("LOCALAPPDATA") or Path.home() / "AppData" / "Local") directory = cache / "RobRunChecker" directory.mkdir(mode=0o700, parents=True, exist_ok=True) path = None try: with tempfile.NamedTemporaryFile(dir=directory, prefix=".scan-", delete=False) as file: path = Path(file.name) file.write(body) os.replace(path, directory / "last-scan.json") finally: if path is not None: path.unlink(missing_ok=True) class NoRedirect(HTTPRedirectHandler): def redirect_request(self, req, fp, code, msg, headers, newurl): return None def upload_scan(body): # The same scan ID is retried so a lost response cannot create a duplicate. request = Request( SITE + "/api/device-check/scans", data=body, method="POST", headers={"Content-Type": "application/json", "User-Agent": USER_AGENT}, ) opener = build_opener(NoRedirect) for attempt in range(2): try: with opener.open(request, timeout=15) as response: if response.status == 200 and json.loads(response.read(1024)).get("state") == "stored": return except HTTPError as error: status = error.code error.close() if status < 500: raise RuntimeError(f"Upload failed (HTTP {status}) / 上传失败") from error except (URLError, OSError, ValueError, AttributeError): pass if not attempt: time.sleep(0.4) raise RuntimeError("Could not upload the scan. Check your connection and try again. / 上传失败,请检查网络后重试。") def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--no-open", action="store_true", help="print the private report link instead of opening a browser") args = parser.parse_args() if sys.version_info < (3, 9): parser.exit(1, "Python 3.9 or later is required. / 需要 Python 3.9 或更新版本。\n") os_name = platform.system() collector = {"Darwin": mac_scan, "Windows": windows_scan}.get(os_name) if not collector: parser.exit(1, "This checker supports macOS and Windows. / 本检测脚本支持 macOS 和 Windows。\n") print("Free scan: system, processor, graphics, memory and disk space are sent to robrun.lol.\n" "免费扫描会将系统、处理器、显卡、内存和磁盘信息发送到 robrun.lol。", file=sys.stderr) try: hardware, language = collector() if not hardware["OS"] or not any(hardware[field] for field in ("CPU", "GPU", "RamGB")): raise RuntimeError("Could not read hardware. / 无法读取电脑配置。") scan_id, body = serialize_scan(hardware) save_scan(body, os_name) upload_scan(body) except (OSError, RuntimeError, ValueError) as error: parser.exit(1, f"{error}\n") chinese = (language or locale.getlocale()[0] or "").lower().startswith("zh") prefix = "/zh" if chinese else "" url = f"{SITE}{prefix}/pc-check/report/#id={scan_id}" opened = False if not args.no_open: try: opened = webbrowser.open(url) except (OSError, webbrowser.Error): pass if opened: print("扫描完成,已打开报告页。" if chinese else "Scan complete. Your report page is open.") else: print(url) if __name__ == "__main__": main()