feat(backend): Phase 1-4 全新開發完成,37/37 TDD 通過
[Phase 0 Reset]
- 清除舊版 app/、alembic/versions/、雜亂測試腳本
- 新 requirements.txt (移除 caldav/redis/keycloak-lib,加入 apscheduler/croniter/docker/paramiko/ping3/dnspython)
[Phase 1 資料庫]
- 9 張資料表 SQLAlchemy Models:tenants / accounts / schedules / schedule_logs /
tenant_schedule_results / account_schedule_results / servers / server_status_logs / system_status_logs
- Alembic migration 001_create_all_tables (已套用到 10.1.0.20:5433/virtual_mis)
- seed.py:schedules 初始 3 筆 / servers 初始 4 筆
[Phase 2 CRUD API]
- GET/POST/PUT/DELETE: /api/v1/tenants / accounts / servers / schedules
- /api/v1/system-status
- 帳號編碼自動產生 (prefix + seq_no 4碼左補0)
- 燈號 (lights) 從最新排程結果取得
[Phase 3 Watchdog]
- APScheduler interval 3分鐘,原子 UPDATE status=Going 防重複執行
- 手動觸發 API: POST /api/v1/schedules/{id}/run
[Phase 4 Service Clients]
- KeycloakClient:vmis-admin realm,REST API (不用 python-keycloak)
- MailClient:Docker Mailserver @ 10.1.0.254:8080,含 MX DNS 驗證
- DockerClient:docker-py 本機 + paramiko SSH 遠端 compose
- NextcloudClient:OCS API user/quota
- SystemChecker:功能驗證 (traefik routers>0 / keycloak token / SMTP EHLO / DB SELECT 1 / ping)
[TDD]
- 37 tests / 37 passed (2.11s)
- SQLite in-memory + StaticPool,無需外部 DB
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
85
backend/app/services/nextcloud_client.py
Normal file
85
backend/app/services/nextcloud_client.py
Normal file
@@ -0,0 +1,85 @@
|
||||
"""
|
||||
NextcloudClient — Nextcloud OCS API
|
||||
管理 NC 使用者的查詢/建立與 quota 統計。
|
||||
"""
|
||||
import logging
|
||||
from typing import Optional
|
||||
import httpx
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
OCS_HEADERS = {"OCS-APIRequest": "true"}
|
||||
TIMEOUT = 15.0
|
||||
|
||||
|
||||
class NextcloudClient:
|
||||
def __init__(self, domain: str, admin_user: str = "admin", admin_password: str = ""):
|
||||
self._base = f"https://{domain}"
|
||||
self._auth = (admin_user, admin_password)
|
||||
|
||||
def user_exists(self, username: str) -> bool:
|
||||
try:
|
||||
resp = httpx.get(
|
||||
f"{self._base}/ocs/v1.php/cloud/users/{username}",
|
||||
auth=self._auth,
|
||||
headers=OCS_HEADERS,
|
||||
timeout=TIMEOUT,
|
||||
)
|
||||
return resp.status_code == 200
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def create_user(self, username: str, password: Optional[str], quota_gb: int = 20) -> bool:
|
||||
try:
|
||||
resp = httpx.post(
|
||||
f"{self._base}/ocs/v1.php/cloud/users",
|
||||
auth=self._auth,
|
||||
headers=OCS_HEADERS,
|
||||
data={
|
||||
"userid": username,
|
||||
"password": password or "",
|
||||
"quota": f"{quota_gb}GB",
|
||||
},
|
||||
timeout=TIMEOUT,
|
||||
)
|
||||
return resp.status_code == 200
|
||||
except Exception as e:
|
||||
logger.error(f"NC create_user({username}) failed: {e}")
|
||||
return False
|
||||
|
||||
def get_user_quota_used_gb(self, username: str) -> Optional[float]:
|
||||
try:
|
||||
resp = httpx.get(
|
||||
f"{self._base}/ocs/v2.php/cloud/users/{username}",
|
||||
auth=self._auth,
|
||||
headers=OCS_HEADERS,
|
||||
timeout=TIMEOUT,
|
||||
)
|
||||
if resp.status_code != 200:
|
||||
return None
|
||||
used_bytes = resp.json().get("ocs", {}).get("data", {}).get("quota", {}).get("used", 0)
|
||||
return round(used_bytes / 1073741824, 4)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def get_total_quota_used_gb(self) -> Optional[float]:
|
||||
"""Sum all users' quota usage"""
|
||||
try:
|
||||
resp = httpx.get(
|
||||
f"{self._base}/ocs/v2.php/cloud/users",
|
||||
auth=self._auth,
|
||||
headers=OCS_HEADERS,
|
||||
params={"limit": 500},
|
||||
timeout=TIMEOUT,
|
||||
)
|
||||
if resp.status_code != 200:
|
||||
return None
|
||||
users = resp.json().get("ocs", {}).get("data", {}).get("users", [])
|
||||
total = 0.0
|
||||
for uid in users:
|
||||
used = self.get_user_quota_used_gb(uid)
|
||||
if used:
|
||||
total += used
|
||||
return round(total, 4)
|
||||
except Exception:
|
||||
return None
|
||||
Reference in New Issue
Block a user