chore(release): bump version to v1.0.1
This commit is contained in:
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,45 @@
|
||||
import json
|
||||
import os
|
||||
from typing import Any, Dict
|
||||
|
||||
|
||||
class StringCatalog:
|
||||
"""Centralized string catalog loader for MyIP applet."""
|
||||
|
||||
_instance = None
|
||||
_catalog: Dict[str, Any] = {}
|
||||
|
||||
def __new__(cls):
|
||||
if cls._instance is None:
|
||||
cls._instance = super(StringCatalog, cls).__new__(cls)
|
||||
cls._instance._load_catalog()
|
||||
return cls._instance
|
||||
|
||||
def _load_catalog(self) -> None:
|
||||
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
catalog_path = os.path.join(base_dir, "catalog", "strings.json")
|
||||
if os.path.exists(catalog_path):
|
||||
with open(catalog_path, "r", encoding="utf-8") as f:
|
||||
self._catalog = json.load(f)
|
||||
else:
|
||||
self._catalog = {}
|
||||
|
||||
def get(self, key_path: str, default: str = "") -> str:
|
||||
parts = key_path.split(".")
|
||||
current = self._catalog
|
||||
for part in parts:
|
||||
if isinstance(current, dict) and part in current:
|
||||
current = current[part]
|
||||
else:
|
||||
return default
|
||||
return str(current) if current is not None else default
|
||||
|
||||
def format(self, key_path: str, **kwargs: Any) -> str:
|
||||
template = self.get(key_path, "")
|
||||
try:
|
||||
return template.format(**kwargs)
|
||||
except KeyError:
|
||||
return template
|
||||
|
||||
|
||||
catalog = StringCatalog()
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
import json
|
||||
import sys
|
||||
from typing import List, Optional
|
||||
|
||||
from src.catalog import catalog
|
||||
from src.resolver import IPResolver
|
||||
|
||||
|
||||
def print_help() -> None:
|
||||
print(f"{catalog.get('app.name')} - {catalog.get('app.tagline')}")
|
||||
print()
|
||||
print(catalog.get("cli.usage"))
|
||||
print()
|
||||
print(catalog.get("cli.options_title"))
|
||||
print(f" -h, --help {catalog.get('cli.opt_help')}")
|
||||
print(f" -V, --version {catalog.get('cli.opt_version')}")
|
||||
print(f" -j, --json {catalog.get('cli.opt_json')}")
|
||||
print(f" -l, --local {catalog.get('cli.opt_local')}")
|
||||
print(f" -p, --public {catalog.get('cli.opt_public')}")
|
||||
print(f" -v, --verbose {catalog.get('cli.opt_verbose')}")
|
||||
|
||||
|
||||
def run_cli(args: Optional[List[str]] = None) -> int:
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
raw_args = args if args is not None else sys.argv[1:]
|
||||
|
||||
if "-h" in raw_args or "--help" in raw_args:
|
||||
print_help()
|
||||
return 0
|
||||
|
||||
if "-V" in raw_args or "--version" in raw_args or "-v" in raw_args and len(raw_args) == 1 and raw_args[0] == "-v":
|
||||
# Check if version vs verbose
|
||||
if "--version" in raw_args or "-V" in raw_args:
|
||||
print(catalog.format("app.version_output", name="MyIP", version="1.0.0", author="Maeve Gallagher"))
|
||||
return 0
|
||||
|
||||
is_json = "-j" in raw_args or "--json" in raw_args
|
||||
is_local_only = "-l" in raw_args or "--local" in raw_args
|
||||
is_public_only = "-p" in raw_args or "--public" in raw_args
|
||||
is_verbose = "-v" in raw_args or "--verbose" in raw_args
|
||||
|
||||
if is_local_only:
|
||||
local_ip = IPResolver.get_local_ip()
|
||||
if is_json:
|
||||
print(json.dumps({"local_ip": local_ip}, indent=2))
|
||||
else:
|
||||
print(local_ip)
|
||||
return 0
|
||||
|
||||
if is_public_only:
|
||||
public_ip = IPResolver.get_public_ip() or catalog.get("output.unknown")
|
||||
if is_json:
|
||||
print(json.dumps({"public_ip": public_ip}, indent=2))
|
||||
else:
|
||||
print(public_ip)
|
||||
return 0
|
||||
|
||||
if is_verbose:
|
||||
info = IPResolver.get_verbose_info()
|
||||
if is_json:
|
||||
print(json.dumps(info, indent=2))
|
||||
else:
|
||||
print(catalog.get("output.verbose_header"))
|
||||
print("-" * 50)
|
||||
print(f" {catalog.get('output.field_hostname'):<20}: {info['hostname']}")
|
||||
print(f" {catalog.get('output.field_local_ip'):<20}: {info['local_ip']}")
|
||||
print(f" {catalog.get('output.field_public_ip'):<20}: {info['public_ip']}")
|
||||
print(f" {catalog.get('output.field_country'):<20}: {info['country']}")
|
||||
print(f" {catalog.get('output.field_region'):<20}: {info['region']}")
|
||||
print(f" {catalog.get('output.field_city'):<20}: {info['city']}")
|
||||
print(f" {catalog.get('output.field_org'):<20}: {info['org']}")
|
||||
print(f" {catalog.get('output.field_timezone'):<20}: {info['timezone']}")
|
||||
if info["interfaces"]:
|
||||
print()
|
||||
print(f" {catalog.get('output.interfaces_header')}")
|
||||
for iface in info["interfaces"]:
|
||||
print(f" - {iface}")
|
||||
return 0
|
||||
|
||||
# Default output: single clean line
|
||||
local_ip = IPResolver.get_local_ip()
|
||||
public_ip = IPResolver.get_public_ip() or catalog.get("output.unknown")
|
||||
|
||||
if is_json:
|
||||
print(json.dumps({"local_ip": local_ip, "public_ip": public_ip}, indent=2))
|
||||
else:
|
||||
print(catalog.format("output.single_line", local_ip=local_ip, public_ip=public_ip))
|
||||
|
||||
return 0
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
import json
|
||||
import socket
|
||||
import urllib.request
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
|
||||
class IPResolver:
|
||||
"""Fast, zero-overhead local and public IP address resolver."""
|
||||
|
||||
PUBLIC_PROVIDERS = [
|
||||
"https://api.ipify.org",
|
||||
"https://icanhazip.com",
|
||||
"https://ifconfig.me/ip",
|
||||
"https://ipecho.net/plain"
|
||||
]
|
||||
|
||||
GEOLOCATION_PROVIDERS = [
|
||||
"https://ipinfo.io/json",
|
||||
"http://ip-api.com/json"
|
||||
]
|
||||
|
||||
@staticmethod
|
||||
def get_local_ip() -> str:
|
||||
"""Determines the primary outbound local IPv4 address using UDP socket routing lookup."""
|
||||
try:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
|
||||
# Does not establish a connection; triggers kernel routing table selection
|
||||
s.connect(("8.8.8.8", 80))
|
||||
ip = s.getsockname()[0]
|
||||
if ip and not ip.startswith("127."):
|
||||
return ip
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
hostname = socket.gethostname()
|
||||
ip = socket.gethostbyname(hostname)
|
||||
if ip:
|
||||
return ip
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return "127.0.0.1"
|
||||
|
||||
@classmethod
|
||||
def get_public_ip(cls, timeout: float = 2.0) -> Optional[str]:
|
||||
"""Resolves public WAN IP address using lightweight HTTP endpoints."""
|
||||
req_headers = {"User-Agent": "curl/7.68.0"}
|
||||
for url in cls.PUBLIC_PROVIDERS:
|
||||
try:
|
||||
req = urllib.request.Request(url, headers=req_headers)
|
||||
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||||
if resp.status == 200:
|
||||
ip = resp.read().decode("utf-8").strip()
|
||||
if ip and len(ip) <= 45: # Valid IPv4 or IPv6 string
|
||||
return ip
|
||||
except Exception:
|
||||
continue
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def get_verbose_info(cls) -> Dict[str, Any]:
|
||||
"""Collects full host, network interface, and public geolocation metadata."""
|
||||
local_ip = cls.get_local_ip()
|
||||
public_ip = cls.get_public_ip()
|
||||
hostname = socket.gethostname()
|
||||
|
||||
info: Dict[str, Any] = {
|
||||
"hostname": hostname,
|
||||
"local_ip": local_ip,
|
||||
"public_ip": public_ip or "Unavailable",
|
||||
"city": "Unavailable",
|
||||
"region": "Unavailable",
|
||||
"country": "Unavailable",
|
||||
"org": "Unavailable",
|
||||
"timezone": "Unavailable",
|
||||
"interfaces": []
|
||||
}
|
||||
|
||||
# Query geolocation
|
||||
for geo_url in cls.GEOLOCATION_PROVIDERS:
|
||||
try:
|
||||
req = urllib.request.Request(geo_url, headers={"User-Agent": "curl/7.68.0"})
|
||||
with urllib.request.urlopen(req, timeout=2.5) as resp:
|
||||
if resp.status == 200:
|
||||
data = json.loads(resp.read().decode("utf-8"))
|
||||
info["city"] = data.get("city") or info["city"]
|
||||
info["region"] = data.get("region") or data.get("regionName") or info["region"]
|
||||
info["country"] = data.get("country") or data.get("countryCode") or info["country"]
|
||||
info["org"] = data.get("org") or data.get("isp") or info["org"]
|
||||
info["timezone"] = data.get("timezone") or info["timezone"]
|
||||
if not public_ip and (data.get("ip") or data.get("query")):
|
||||
info["public_ip"] = data.get("ip") or data.get("query")
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
# Enumerate host addresses
|
||||
try:
|
||||
addr_info = socket.getaddrinfo(hostname, None)
|
||||
seen_ips = set()
|
||||
for item in addr_info:
|
||||
ip_candidate = item[4][0]
|
||||
if ip_candidate not in seen_ips:
|
||||
seen_ips.add(ip_candidate)
|
||||
info["interfaces"].append(ip_candidate)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return info
|
||||
Reference in New Issue
Block a user