Spaces:
Sleeping
Sleeping
Download storage.py from WACATW/cloud-camera: direct link, hf CLI and curl.
- Browser
- Download file 4.39 kB
-
https://huggingface.co/spaces/WACATW/cloud-camera/resolve/main/storage.py
- Command line
-
hf download hf://spaces/WACATW/cloud-camera/storage.py
-
curl -L -o storage.py https://huggingface.co/spaces/WACATW/cloud-camera/resolve/main/storage.py
4.39 kB
| """云端相机 - 存储与用户管理 | |
| 目录结构(默认根目录 /data,Hugging Face Space 持久化磁盘): | |
| /data/ | |
| .secret # 签名密钥(首次启动自动生成,持久保存) | |
| .users/<name>.json # 用户 PIN 哈希 | |
| <name>/index.json # 相册索引(照片元数据列表) | |
| <name>/<id>.jpg # 原图 | |
| <name>/<id>_thumb.jpg# 缩略图 | |
| """ | |
| import hashlib | |
| import hmac | |
| import json | |
| import os | |
| import re | |
| import time | |
| import uuid | |
| from pathlib import Path | |
| DATA_DIR = Path(os.environ.get("DATA_DIR", "/data")) | |
| USERS_DIR = DATA_DIR / ".users" | |
| USERNAME_RE = re.compile(r"^[\w\u4e00-\u9fff-]{1,24}$") | |
| PIN_RE = re.compile(r"^.{4,20}$") | |
| def ensure_dirs() -> None: | |
| USERS_DIR.mkdir(parents=True, exist_ok=True) | |
| def _user_file(username: str) -> Path: | |
| return USERS_DIR / f"{username}.json" | |
| def _user_dir(username: str) -> Path: | |
| return DATA_DIR / username | |
| def _index_file(username: str) -> Path: | |
| return _user_dir(username) / "index.json" | |
| def valid_username(username: str) -> bool: | |
| return bool(username) and bool(USERNAME_RE.match(username)) | |
| def valid_pin(pin: str) -> bool: | |
| return bool(pin) and bool(PIN_RE.match(pin)) | |
| def _hash_pin(pin: str, salt: str) -> str: | |
| return hashlib.sha256(f"{salt}:{pin}".encode("utf-8")).hexdigest() | |
| def user_exists(username: str) -> bool: | |
| return _user_file(username).exists() | |
| def create_user(username: str, pin: str) -> None: | |
| salt = uuid.uuid4().hex | |
| _user_file(username).write_text( | |
| json.dumps({"salt": salt, "pin_hash": _hash_pin(pin, salt)}), | |
| encoding="utf-8", | |
| ) | |
| _user_dir(username).mkdir(parents=True, exist_ok=True) | |
| _index_file(username).write_text(json.dumps({"photos": []}), encoding="utf-8") | |
| def verify_user(username: str, pin: str) -> bool: | |
| f = _user_file(username) | |
| if not f.exists(): | |
| return False | |
| try: | |
| data = json.loads(f.read_text(encoding="utf-8")) | |
| except Exception: | |
| return False | |
| return _hash_pin(pin, data.get("salt", "")) == data.get("pin_hash", "") | |
| def list_photos(username: str) -> list: | |
| f = _index_file(username) | |
| if not f.exists(): | |
| return [] | |
| try: | |
| return json.loads(f.read_text(encoding="utf-8")).get("photos", []) | |
| except Exception: | |
| return [] | |
| def add_photo(username: str, photo: dict) -> None: | |
| f = _index_file(username) | |
| data = {"photos": []} | |
| if f.exists(): | |
| try: | |
| data = json.loads(f.read_text(encoding="utf-8")) | |
| except Exception: | |
| data = {"photos": []} | |
| data.setdefault("photos", []).insert(0, photo) | |
| f.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8") | |
| def remove_photo(username: str, photo_id: str) -> bool: | |
| f = _index_file(username) | |
| if not f.exists(): | |
| return False | |
| try: | |
| data = json.loads(f.read_text(encoding="utf-8")) | |
| except Exception: | |
| return False | |
| before = len(data.get("photos", [])) | |
| data["photos"] = [p for p in data.get("photos", []) if p["id"] != photo_id] | |
| f.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8") | |
| return len(data["photos"]) < before | |
| # ---------- 图片访问签名 ---------- | |
| def get_secret() -> bytes: | |
| """签名密钥:优先环境变量 SIGN_SECRET,否则用持久化的随机密钥。""" | |
| env = os.environ.get("SIGN_SECRET") | |
| if env: | |
| return env.encode("utf-8") | |
| f = DATA_DIR / ".secret" | |
| if f.exists(): | |
| return f.read_text(encoding="utf-8").strip().encode("utf-8") | |
| s = uuid.uuid4().hex | |
| f.write_text(s, encoding="utf-8") | |
| return s.encode("utf-8") | |
| def make_token(username: str, photo_id: str, ttl: int = 86400) -> str: | |
| """为图片生成带过期时间的访问令牌。""" | |
| expires = int(time.time()) + ttl | |
| msg = f"{username}/{photo_id}/{expires}".encode("utf-8") | |
| sig = hmac.new(get_secret(), msg, hashlib.sha256).hexdigest() | |
| return f"{expires}.{sig}" | |
| def verify_token(username: str, photo_id: str, token: str) -> bool: | |
| try: | |
| expires_str, sig = token.split(".", 1) | |
| expires = int(expires_str) | |
| except Exception: | |
| return False | |
| if time.time() > expires: | |
| return False | |
| msg = f"{username}/{photo_id}/{expires}".encode("utf-8") | |
| expect = hmac.new(get_secret(), msg, hashlib.sha256).hexdigest() | |
| return hmac.compare_digest(expect, sig) | |