""" Storage adapter — transparent local-disk vs. GCS-backed file storage. Local mode (default): reads/writes files in CWD. Cloud mode (GCS_BUCKET env var set): reads/writes blobs in that bucket. Usage: from modules.storage import load_bytes, save_bytes, load_json, save_json data = load_json("users.json", default={}) save_json("users.json", data) """ import os import json _BUCKET_NAME = os.environ.get("GCS_BUCKET", "").strip() _client = None _bucket = None def _get_bucket(): global _client, _bucket if _bucket is not None: return _bucket if not _BUCKET_NAME: return None from google.cloud import storage as gcs _client = gcs.Client() _bucket = _client.bucket(_BUCKET_NAME) return _bucket def _is_gcs(): return bool(_BUCKET_NAME) def _normalize(name): """Strip leading ./ so GCS blob names match uploaded filenames.""" if isinstance(name, str) and name.startswith("./"): return name[2:] return name def load_bytes(name): """Return bytes of file `name`, or None if missing.""" name = _normalize(name) if _is_gcs(): try: blob = _get_bucket().blob(name) if not blob.exists(): return None return blob.download_as_bytes() except Exception as e: print("STORAGE read failed for " + name + ": " + str(e)) return None else: if not os.path.isfile(name): return None try: with open(name, "rb") as f: return f.read() except Exception as e: print("STORAGE read failed for " + name + ": " + str(e)) return None def save_bytes(name, data): """Write bytes `data` to file `name`. Returns True on success.""" name = _normalize(name) if isinstance(data, str): data = data.encode("utf-8") if _is_gcs(): try: blob = _get_bucket().blob(name) blob.upload_from_string(data) return True except Exception as e: print("STORAGE write failed for " + name + ": " + str(e)) return False else: try: with open(name, "wb") as f: f.write(data) return True except Exception as e: print("STORAGE write failed for " + name + ": " + str(e)) return False def load_json(name, default=None): raw = load_bytes(name) if raw is None: return default try: return json.loads(raw.decode("utf-8")) except Exception as e: print("STORAGE json parse failed for " + name + ": " + str(e)) return default def save_json(name, data): try: return save_bytes(name, json.dumps(data, indent=2).encode("utf-8")) except Exception as e: print("STORAGE json dump failed for " + name + ": " + str(e)) return False def load_text(name, default=""): raw = load_bytes(name) if raw is None: return default try: return raw.decode("utf-8") except Exception: return default def save_text(name, text): return save_bytes(name, text.encode("utf-8")) def append_text(name, line): """Append a line to a text file (reads, appends, writes back).""" existing = load_text(name, "") return save_text(name, existing + line) def delete_bytes(name): """Delete file/blob `name`. Returns True on success.""" name = _normalize(name) if _is_gcs(): try: _get_bucket().blob(name).delete() return True except Exception as e: print("STORAGE delete failed for " + name + ": " + str(e)) return False else: try: if os.path.isfile(name): os.remove(name) return True except Exception as e: print("STORAGE delete failed for " + name + ": " + str(e)) return False def list_prefix(prefix): """Return all object names under `prefix` (GCS blobs or local files).""" prefix = _normalize(prefix) if _is_gcs(): try: return [b.name for b in _get_bucket().list_blobs(prefix=prefix)] except Exception as e: print("STORAGE list failed for " + prefix + ": " + str(e)) return [] try: out = [] for root, _dirs, files in os.walk(prefix): for f in files: out.append(os.path.join(root, f).replace(os.sep, "/")) return out except Exception: return []