110 lines
4.2 KiB
Python
110 lines
4.2 KiB
Python
import json
|
|
import time
|
|
from pathlib import Path
|
|
from typing import Any, Dict, List, Optional
|
|
import requests
|
|
|
|
|
|
DEFAULT_REGISTRY_URL = "https://git.luxhebros.com/api/v1/repos/admin/gravitiny/raw/registry/index.json"
|
|
|
|
|
|
class RegistryClient:
|
|
"""Fetches, caches, and searches remote applets from the central Gravitiny registry."""
|
|
|
|
def __init__(self, registry_url: Optional[str] = None, cache_ttl_seconds: int = 300):
|
|
self.registry_url = registry_url or DEFAULT_REGISTRY_URL
|
|
self.cache_ttl = cache_ttl_seconds
|
|
self.cache_file = Path.home() / ".gravitiny" / "registry_cache.json"
|
|
|
|
def _get_local_fallback(self) -> Optional[Dict[str, Any]]:
|
|
"""Checks for local workspace registry/index.json if offline or developing."""
|
|
base_dir = Path(__file__).resolve().parent.parent.parent
|
|
local_index = base_dir / "registry" / "index.json"
|
|
if local_index.exists():
|
|
try:
|
|
with open(local_index, "r", encoding="utf-8") as f:
|
|
return json.load(f)
|
|
except Exception:
|
|
pass
|
|
return None
|
|
|
|
def fetch_index(self, force_refresh: bool = False) -> Dict[str, Any]:
|
|
"""Fetches the remote registry index, using cache when fresh."""
|
|
# 1. Check local cache
|
|
if not force_refresh and self.cache_file.exists():
|
|
try:
|
|
with open(self.cache_file, "r", encoding="utf-8") as f:
|
|
cached = json.load(f)
|
|
cache_time = cached.get("_cached_at", 0)
|
|
if time.time() - cache_time < self.cache_ttl:
|
|
return cached.get("data", {})
|
|
except Exception:
|
|
pass
|
|
|
|
# 2. Fetch from remote HTTP
|
|
try:
|
|
resp = requests.get(self.registry_url, timeout=5)
|
|
if resp.status_code == 200:
|
|
data = resp.json()
|
|
# Save to cache
|
|
self.cache_file.parent.mkdir(parents=True, exist_ok=True)
|
|
with open(self.cache_file, "w", encoding="utf-8") as f:
|
|
json.dump({"_cached_at": time.time(), "data": data}, f, indent=2)
|
|
return data
|
|
except Exception:
|
|
pass
|
|
|
|
# 3. Fallback to cached version even if expired
|
|
if self.cache_file.exists():
|
|
try:
|
|
with open(self.cache_file, "r", encoding="utf-8") as f:
|
|
return json.load(f).get("data", {})
|
|
except Exception:
|
|
pass
|
|
|
|
# 4. Fallback to local workspace index
|
|
local_fallback = self._get_local_fallback()
|
|
if local_fallback:
|
|
return local_fallback
|
|
|
|
return {}
|
|
|
|
def search(self, query: str = "", force_refresh: bool = False) -> List[Dict[str, Any]]:
|
|
"""Searches across applet id, name, description, tags, and author. Empty query returns all."""
|
|
clean_q = query.strip().lower()
|
|
index = self.fetch_index(force_refresh=force_refresh)
|
|
applets = index.get("applets", {})
|
|
|
|
if not clean_q or clean_q in ["all", "*", "--all", "-a"]:
|
|
return list(applets.values())
|
|
|
|
results: List[Dict[str, Any]] = []
|
|
|
|
for applet_id, info in applets.items():
|
|
name = info.get("name", "").lower()
|
|
desc = info.get("description", "").lower()
|
|
author = info.get("author", "").lower()
|
|
tags = [t.lower() for t in info.get("tags", [])]
|
|
|
|
if (
|
|
clean_q in applet_id.lower()
|
|
or clean_q in name
|
|
or clean_q in desc
|
|
or clean_q in author
|
|
or any(clean_q in t for t in tags)
|
|
):
|
|
results.append(info)
|
|
|
|
return results
|
|
|
|
def get_applet(self, applet_id: str, force_refresh: bool = False) -> Optional[Dict[str, Any]]:
|
|
"""Retrieves metadata for a specific remote applet."""
|
|
clean_id = applet_id.strip().lower()
|
|
index = self.fetch_index(force_refresh=force_refresh)
|
|
applets = index.get("applets", {})
|
|
if clean_id not in applets and not force_refresh:
|
|
# Retry with force refresh once
|
|
index = self.fetch_index(force_refresh=True)
|
|
applets = index.get("applets", {})
|
|
return applets.get(clean_id)
|