File size: 6,526 Bytes
5dbdea7
 
 
 
7dc58b6
5dbdea7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7dc58b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5dbdea7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce673a5
 
a4999bf
 
 
 
 
 
 
 
 
 
 
 
ce673a5
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
import os
from contextlib import asynccontextmanager

from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import HTMLResponse, JSONResponse, Response

from app.core.dashboard import render_dashboard
from app.core.platform import MonitoringPlatform


platform = MonitoringPlatform()


@asynccontextmanager
async def lifespan(app):
    if os.getenv("DISABLE_WORKER", "false").lower() not in ("1", "true", "yes", "on"):
        platform.start()
    yield
    platform.stop()


app = FastAPI(title="监控平台", version="1.0.0", lifespan=lifespan)


@app.get("/", response_class=HTMLResponse)
def dashboard():
    return render_dashboard()


@app.get("/manifest.webmanifest")
def manifest():
    return JSONResponse({
        "name": "监控平台",
        "short_name": "监控",
        "description": "价格、财务指标和脚本健康统一监控",
        "start_url": "/",
        "scope": "/",
        "display": "standalone",
        "background_color": "#f3f5f8",
        "theme_color": "#111827",
        "icons": [
            {
                "src": "/icons/icon.svg",
                "sizes": "any",
                "type": "image/svg+xml",
                "purpose": "any maskable",
            }
        ],
    }, media_type="application/manifest+json")


@app.get("/service-worker.js")
def service_worker():
    script = """
const CACHE_NAME = "coinpush-pwa-v1";
const APP_SHELL = ["/", "/manifest.webmanifest", "/icons/icon.svg"];

self.addEventListener("install", (event) => {
  event.waitUntil(caches.open(CACHE_NAME).then((cache) => cache.addAll(APP_SHELL)));
  self.skipWaiting();
});

self.addEventListener("activate", (event) => {
  event.waitUntil(
    caches.keys().then((keys) => Promise.all(
      keys.filter((key) => key !== CACHE_NAME).map((key) => caches.delete(key))
    ))
  );
  self.clients.claim();
});

self.addEventListener("fetch", (event) => {
  const url = new URL(event.request.url);
  if (url.pathname.startsWith("/api/") || url.pathname === "/healthz") return;

  if (event.request.mode === "navigate") {
    event.respondWith(
      fetch(event.request)
        .then((response) => {
          const copy = response.clone();
          caches.open(CACHE_NAME).then((cache) => cache.put("/", copy));
          return response;
        })
        .catch(() => caches.match("/") || new Response("Offline", {status: 503}))
    );
    return;
  }

  event.respondWith(
    caches.match(event.request).then((cached) => cached || fetch(event.request))
  );
});
""".strip()
    return Response(script, media_type="application/javascript")


@app.get("/icons/icon.svg")
def app_icon():
    svg = """
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
  <rect width="512" height="512" rx="96" fill="#111827"/>
  <path d="M118 335h276" stroke="#f9fafb" stroke-width="34" stroke-linecap="round"/>
  <path d="M142 302l72-78 58 45 98-118" fill="none" stroke="#2dd4bf" stroke-width="34" stroke-linecap="round" stroke-linejoin="round"/>
  <circle cx="142" cy="302" r="22" fill="#f59e0b"/>
  <circle cx="214" cy="224" r="22" fill="#f9fafb"/>
  <circle cx="272" cy="269" r="22" fill="#f59e0b"/>
  <circle cx="370" cy="151" r="22" fill="#f9fafb"/>
</svg>
""".strip()
    return Response(svg, media_type="image/svg+xml")


@app.get("/healthz")
def healthz():
    status = platform.status()
    errors = [m for m in status["monitors"] if m["status"] == "error"]
    return {
        "ok": len(errors) == 0,
        "started": status["started"],
        "error_monitors": len(errors),
    }


@app.get("/api/status")
def api_status():
    return JSONResponse(platform.status())


@app.get("/api/monitors")
def api_monitors():
    return platform.store.list_monitors()


@app.post("/api/monitors/{monitor_id:path}/pause")
def api_pause_monitor(monitor_id: str):
    try:
        return platform.set_monitor_paused(monitor_id, True)
    except KeyError as exc:
        raise HTTPException(status_code=404, detail=str(exc)) from exc


@app.post("/api/monitors/{monitor_id:path}/resume")
def api_resume_monitor(monitor_id: str):
    try:
        return platform.set_monitor_paused(monitor_id, False)
    except KeyError as exc:
        raise HTTPException(status_code=404, detail=str(exc)) from exc


@app.get("/api/alerts")
def api_alerts(limit: int = 50):
    return platform.store.recent_alerts(limit)


@app.get("/api/events")
def api_events(limit: int = 80):
    return platform.store.recent_events(limit)


@app.get("/api/config")
def api_get_config():
    return platform.get_config()


@app.put("/api/config")
async def api_update_config(request: Request):
    try:
        cfg = await request.json()
        if not isinstance(cfg, dict) or "coins" not in cfg or "global" not in cfg:
            raise ValueError("配置必须包含 coins 和 global")
        return platform.update_config(cfg)
    except Exception as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc


@app.post("/api/calibrate")
def api_calibrate_all():
    try:
        return platform.calibrate_all()
    except Exception as exc:
        raise HTTPException(status_code=500, detail=str(exc)) from exc


@app.post("/api/calibrate/{coin}")
def api_calibrate_coin(coin: str):
    try:
        return platform.calibrate_coin(coin)
    except KeyError as exc:
        raise HTTPException(status_code=404, detail=str(exc)) from exc
    except Exception as exc:
        raise HTTPException(status_code=500, detail=str(exc)) from exc


@app.get("/api/crypto/{coin}/klines")
def api_crypto_klines(coin: str, interval: str = "1h", limit: int = 120):
    try:
        return JSONResponse(platform.get_klines(coin, interval, limit))
    except KeyError as exc:
        raise HTTPException(status_code=404, detail=str(exc)) from exc
    except (TypeError, ValueError) as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc
    except Exception as exc:
        raise HTTPException(status_code=502, detail=str(exc)) from exc


@app.get("/api/market-move/config")
def api_get_market_move_config():
    return platform.get_market_move_config()


@app.put("/api/market-move/config")
async def api_update_market_move_config(request: Request):
    try:
        cfg = await request.json()
        if not isinstance(cfg, dict) or "coins" not in cfg:
            raise ValueError("配置必须包含 coins")
        return platform.update_market_move_config(cfg)
    except Exception as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc