feiver commited on
Commit
ea4b010
·
verified ·
1 Parent(s): b3a82cc

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +279 -0
app.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import asyncio
4
+ import time
5
+
6
+ from starlette.applications import Starlette
7
+ from starlette.requests import Request
8
+ from starlette.responses import Response, StreamingResponse, FileResponse, JSONResponse
9
+ import httpx
10
+
11
+ # telegram-bot-api 上游地址
12
+ # 容器内 telegram-bot-api 监听 127.0.0.1:8081,代理层转发请求到这里
13
+ UPSTREAM = f"http://127.0.0.1:{os.environ.get('TELEGRAM_API_PORT', '8081')}"
14
+ app = Starlette(debug=False)
15
+
16
+ # 文件下载配置
17
+ WORK_DIR = os.environ.get("TELEGRAM_WORK_DIR", "/tmp/telegram-bot-api-data")
18
+ DOWNLOAD_WAIT_SECONDS = float(os.environ.get("TELEGRAM_DOWNLOAD_WAIT_SECONDS", "8"))
19
+ DOWNLOAD_POLL_INTERVAL_MS = int(os.environ.get("TELEGRAM_DOWNLOAD_POLL_INTERVAL_MS", "200"))
20
+
21
+ _INFLIGHT_LOCKS: dict[str, asyncio.Lock] = {}
22
+ _INFLIGHT_LAST_SEEN: dict[str, float] = {}
23
+
24
+ def _inflight_key(token_enc: str | None, file_id: str | None) -> str:
25
+ return f"{token_enc or ''}:{file_id or ''}"
26
+
27
+ def _get_inflight_lock(key: str) -> asyncio.Lock:
28
+ lock = _INFLIGHT_LOCKS.get(key)
29
+ if lock is None:
30
+ lock = asyncio.Lock()
31
+ _INFLIGHT_LOCKS[key] = lock
32
+ _INFLIGHT_LAST_SEEN[key] = time.time()
33
+ return lock
34
+
35
+ def _cleanup_inflight_locks(max_entries: int = 1024, ttl_seconds: float = 300.0) -> None:
36
+ if len(_INFLIGHT_LOCKS) <= max_entries:
37
+ return
38
+ now = time.time()
39
+ for key, lock in list(_INFLIGHT_LOCKS.items()):
40
+ last = _INFLIGHT_LAST_SEEN.get(key, 0.0)
41
+ if (now - last) > ttl_seconds and (not lock.locked()):
42
+ _INFLIGHT_LOCKS.pop(key, None)
43
+ _INFLIGHT_LAST_SEEN.pop(key, None)
44
+
45
+ def _normalize_proxy_prefix(raw: str | None) -> str:
46
+ s = str(raw or "").strip()
47
+ if not s or s == "/":
48
+ return ""
49
+ if not s.startswith("/"):
50
+ s = "/" + s
51
+ return s.rstrip("/")
52
+
53
+ def _normalize_bot_api_file_path(raw_fp: str | None, token_enc: str | None) -> str:
54
+ if not raw_fp:
55
+ return ""
56
+
57
+ fp = str(raw_fp).replace("\\", "/").lstrip("/")
58
+
59
+ if token_enc:
60
+ marker = f"/{token_enc}/"
61
+ idx = fp.find(marker)
62
+ if idx >= 0:
63
+ fp = fp[idx + len(marker) :]
64
+ elif fp.startswith(f"{token_enc}/"):
65
+ fp = fp[len(token_enc) + 1 :]
66
+
67
+ parts = [p for p in fp.split("/") if p]
68
+ roots = {
69
+ "documents",
70
+ "photos",
71
+ "videos",
72
+ "video_notes",
73
+ "voice",
74
+ "audio",
75
+ "animation",
76
+ "animations",
77
+ "stickers",
78
+ "files",
79
+ "thumbnails",
80
+ "profile_photos",
81
+ }
82
+ for i, p in enumerate(parts):
83
+ if p in roots:
84
+ return "/".join(parts[i:])
85
+ return fp
86
+
87
+ def _build_local_candidates(work_dir: str, token_enc: str | None, rel_path: str | None) -> list[str]:
88
+ candidates = []
89
+ rp = str(rel_path or "").strip().lstrip("/")
90
+ if token_enc and rp:
91
+ candidates.append(os.path.join(work_dir, token_enc, rp))
92
+ if rp:
93
+ candidates.append(os.path.join(work_dir, rp))
94
+ return candidates
95
+
96
+ def _try_file_response(candidates: list[str]):
97
+ for p in candidates:
98
+ try:
99
+ if p and os.path.isfile(p):
100
+ return FileResponse(p)
101
+ except Exception:
102
+ pass
103
+ return None
104
+
105
+ async def root(request: Request):
106
+ return JSONResponse({"ok": True})
107
+
108
+ async def proxy(request: Request):
109
+ path = request.path_params.get("path", "")
110
+ # 兜底:如果下游请求把 file_path 带成了“工作目录前缀”,这里直接改写成相对路径再转发给 telegram-bot-api
111
+ path_for_upstream = path.lstrip("/")
112
+ if path_for_upstream.startswith("file/"):
113
+ # 形如:file/bot<TOKEN>/<file_path>
114
+ # 我们只需要把 <file_path> 规范化成 documents/... 这种相对路径
115
+ rest = path_for_upstream[len("file/") :]
116
+ if rest.startswith("bot"):
117
+ token_enc = rest[3:].split("/", 1)[0] or None
118
+ after_bot = rest.split("/", 1)[1] if "/" in rest else ""
119
+ fixed = _normalize_bot_api_file_path(after_bot, token_enc)
120
+ if fixed:
121
+ path_for_upstream = f"file/bot{token_enc}/{fixed}"
122
+
123
+ if path_for_upstream.startswith("file/"):
124
+ rest = path_for_upstream[len("file/") :]
125
+ token_enc = None
126
+ rel = ""
127
+ if rest.startswith("bot"):
128
+ token_enc = rest[3:].split("/", 1)[0] or None
129
+ rel = rest.split("/", 1)[1] if "/" in rest else ""
130
+ rel_fixed = _normalize_bot_api_file_path(rel, token_enc)
131
+
132
+ candidates = _build_local_candidates(WORK_DIR, token_enc, rel_fixed)
133
+ resp = _try_file_response(candidates)
134
+ if resp is not None:
135
+ return resp
136
+
137
+ # 如果本地没有这个文件(HF 不持久化),允许 CloudPaste 通过 query 传入 file_id 来触发回源下载:
138
+ # query 上多带一个 file_id(例如 ?file_id=xxx)
139
+ file_id = request.query_params.get("file_id") or request.query_params.get("fid")
140
+ if token_enc and file_id:
141
+ # 防抖:同一个 (token,file_id) 的回源下载只触发一次,避免并发 Range 请求重复打 getFile/重复等待落盘
142
+ key = _inflight_key(token_enc, str(file_id))
143
+ lock = _get_inflight_lock(key)
144
+ try:
145
+ async with lock:
146
+ resp_again = _try_file_response(_build_local_candidates(WORK_DIR, token_enc, rel_fixed))
147
+ if resp_again is not None:
148
+ return resp_again
149
+
150
+ async with httpx.AsyncClient(timeout=None, follow_redirects=True) as client:
151
+ r = await client.get(f"{UPSTREAM}/bot{token_enc}/getFile", params={"file_id": file_id})
152
+ payload = None
153
+ try:
154
+ payload = r.json()
155
+ except Exception:
156
+ payload = None
157
+
158
+ if r.status_code == 200 and isinstance(payload, dict) and payload.get("ok") is True:
159
+ fp = None
160
+ try:
161
+ fp = (payload.get("result") or {}).get("file_path")
162
+ except Exception:
163
+ fp = None
164
+
165
+ rel2 = _normalize_bot_api_file_path(fp if isinstance(fp, str) else None, token_enc)
166
+ if rel2:
167
+ candidates2 = _build_local_candidates(WORK_DIR, token_enc, rel2)
168
+
169
+ waited = 0.0
170
+ interval = max(0.05, DOWNLOAD_POLL_INTERVAL_MS / 1000.0)
171
+ max_wait = max(0.0, DOWNLOAD_WAIT_SECONDS)
172
+ while waited <= max_wait:
173
+ resp2 = _try_file_response(candidates2)
174
+ if resp2 is not None:
175
+ return resp2
176
+ if waited >= max_wait:
177
+ break
178
+ await asyncio.sleep(interval)
179
+ waited += interval
180
+ finally:
181
+ _cleanup_inflight_locks()
182
+
183
+ url = f"{UPSTREAM}/{path_for_upstream}"
184
+
185
+ params = list(request.query_params.multi_items())
186
+
187
+ headers = dict(request.headers)
188
+ headers.pop("host", None)
189
+
190
+ async def iter_request_body():
191
+ async for chunk in request.stream():
192
+ yield chunk
193
+
194
+
195
+ is_file_download = path_for_upstream.startswith("file/")
196
+ is_get_file = "/getFile" in ("/" + path_for_upstream)
197
+
198
+ passthrough_allow = {
199
+ "content-type",
200
+ "content-disposition",
201
+ "accept-ranges",
202
+ "content-range",
203
+ "etag",
204
+ "cache-control",
205
+ "last-modified",
206
+ }
207
+
208
+ client = httpx.AsyncClient(timeout=None, follow_redirects=True)
209
+ if not is_file_download:
210
+ try:
211
+ r = await client.request(
212
+ request.method,
213
+ url,
214
+ params=params,
215
+ headers=headers,
216
+ content=iter_request_body(),
217
+ )
218
+ resp_headers = {k: v for k, v in r.headers.items() if k.lower() in passthrough_allow}
219
+ resp_headers.pop("content-length", None)
220
+ resp_headers.pop("Content-Length", None)
221
+
222
+ content_type = (r.headers.get("content-type") or "").lower()
223
+ if is_get_file and r.status_code == 200 and "application/json" in content_type:
224
+ try:
225
+ payload = r.json()
226
+ if isinstance(payload, dict) and payload.get("ok") is True and isinstance(payload.get("result"), dict):
227
+ result = payload.get("result") or {}
228
+ fp = result.get("file_path")
229
+ token_enc = None
230
+ p = path_for_upstream.lstrip("/")
231
+ if p.startswith("bot"):
232
+ token_enc = p[3:].split("/", 1)[0] or None
233
+
234
+ fixed = _normalize_bot_api_file_path(fp if isinstance(fp, str) else None, token_enc)
235
+ if fixed:
236
+ result["file_path"] = fixed
237
+ payload["result"] = result
238
+ body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
239
+ resp_headers.setdefault("content-type", "application/json")
240
+ resp_headers.pop("content-length", None)
241
+ resp_headers.pop("Content-Length", None)
242
+ return Response(content=body, status_code=r.status_code, headers=resp_headers)
243
+ except Exception:
244
+ pass
245
+
246
+ return Response(content=r.content, status_code=r.status_code, headers=resp_headers)
247
+ finally:
248
+ await client.aclose()
249
+
250
+ req = client.build_request(
251
+ request.method,
252
+ url,
253
+ params=params,
254
+ headers=headers,
255
+ content=iter_request_body(),
256
+ )
257
+ r = await client.send(req, stream=True)
258
+ resp_headers = {k: v for k, v in r.headers.items() if k.lower() in passthrough_allow}
259
+
260
+ async def iter_response():
261
+ try:
262
+ async for chunk in r.aiter_bytes():
263
+ yield chunk
264
+ finally:
265
+ try:
266
+ await r.aclose()
267
+ finally:
268
+ await client.aclose()
269
+
270
+ return StreamingResponse(iter_response(), status_code=r.status_code, headers=resp_headers)
271
+
272
+ _PROXY_PREFIX = _normalize_proxy_prefix(os.environ.get("TELEGRAM_PROXY_PREFIX", "/tg"))
273
+ _PROXY_ROUTE = f"{_PROXY_PREFIX}/{{path:path}}" if _PROXY_PREFIX else "/{path:path}"
274
+ app.add_route("/", root, methods=["GET"])
275
+ app.add_route(
276
+ _PROXY_ROUTE,
277
+ proxy,
278
+ methods=["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"],
279
+ )