veltrixcode commited on
Commit
6e19694
·
verified ·
1 Parent(s): d40c621

Delete main.py

Browse files
Files changed (1) hide show
  1. main.py +0 -268
main.py DELETED
@@ -1,268 +0,0 @@
1
- import json
2
- import re
3
- from urllib.parse import urljoin, urlparse, urlencode, urlunparse
4
-
5
- import httpx
6
- from fastapi import FastAPI, Request, Response
7
-
8
- app = FastAPI(title="HLS Media Proxy")
9
-
10
- # ---------------------------------------------------------------------------
11
- # Constants
12
- # ---------------------------------------------------------------------------
13
-
14
- FORWARDED_RESPONSE_HEADERS = [
15
- "accept-ranges",
16
- "cache-control",
17
- "content-length",
18
- "content-range",
19
- "content-type",
20
- "etag",
21
- "last-modified",
22
- ]
23
-
24
- BLOCKED_UPSTREAM_HEADERS = {
25
- "accept-encoding",
26
- "connection",
27
- "content-length",
28
- "host",
29
- "range",
30
- "transfer-encoding",
31
- "te",
32
- "upgrade",
33
- "proxy-authorization",
34
- "proxy-connection",
35
- }
36
-
37
- HEADER_NAME_RE = re.compile(r"^[A-Za-z0-9-]+$")
38
-
39
- CORS_HEADERS = {
40
- "Access-Control-Allow-Origin": "*",
41
- "Access-Control-Allow-Methods": "GET, HEAD, OPTIONS",
42
- "Access-Control-Allow-Headers": "Range, Content-Type",
43
- "Access-Control-Expose-Headers": "Accept-Ranges, Content-Length, Content-Range, Content-Type",
44
- "Access-Control-Max-Age": "86400",
45
- }
46
-
47
- # ---------------------------------------------------------------------------
48
- # Helpers
49
- # ---------------------------------------------------------------------------
50
-
51
- def parse_custom_headers(raw: str | None) -> dict | None:
52
- if not raw:
53
- return {}
54
- try:
55
- parsed = json.loads(raw)
56
- except (json.JSONDecodeError, ValueError):
57
- return None
58
- if not isinstance(parsed, dict):
59
- return None
60
- safe = {}
61
- for name, value in parsed.items():
62
- if not HEADER_NAME_RE.match(name):
63
- continue
64
- if name.lower() in BLOCKED_UPSTREAM_HEADERS:
65
- continue
66
- if not isinstance(value, str):
67
- continue
68
- safe[name] = value
69
- return safe
70
-
71
-
72
- def build_proxy_url(base_url: str, target_url: str, referer: str, origin: str,
73
- priority: str, custom_headers: str | None) -> str:
74
- parsed = urlparse(base_url)
75
- params: dict[str, str] = {
76
- "url": target_url,
77
- "referer": referer,
78
- "origin": origin,
79
- }
80
- if priority:
81
- params["priority"] = priority
82
- if custom_headers:
83
- params["headers"] = custom_headers
84
- return urlunparse(parsed._replace(query=urlencode(params)))
85
-
86
-
87
- def rewrite_playlist(base_request_url: str, playlist: str, upstream_url: str,
88
- referer: str, origin: str, priority: str,
89
- custom_headers: str | None) -> str:
90
-
91
- def rewrite_entry(value: str) -> str:
92
- if not value or value.startswith("data:"):
93
- return value
94
- resolved = urljoin(upstream_url, value)
95
- return build_proxy_url(base_request_url, resolved, referer, origin, priority, custom_headers)
96
-
97
- def replace_uri(m: re.Match) -> str:
98
- return f'URI="{rewrite_entry(m.group(1))}"'
99
-
100
- result = re.sub(r'URI="([^"]+)"', replace_uri, playlist)
101
-
102
- lines = []
103
- for line in result.split("\n"):
104
- trimmed = line.strip()
105
- if not trimmed or trimmed.startswith("#"):
106
- lines.append(line)
107
- else:
108
- lines.append(rewrite_entry(trimmed))
109
- return "\n".join(lines)
110
-
111
-
112
- def copy_response_headers(source: httpx.Headers, overrides: dict | None = None) -> dict:
113
- headers: dict[str, str] = {}
114
- for name in FORWARDED_RESPONSE_HEADERS:
115
- value = source.get(name)
116
- if value:
117
- headers[name] = value
118
- if overrides:
119
- headers.update(overrides)
120
- headers["Cache-Control"] = source.get("cache-control", "public, max-age=300")
121
- return headers
122
-
123
-
124
- def json_response(data: dict, status: int = 200) -> Response:
125
- return Response(
126
- content=json.dumps(data),
127
- status_code=status,
128
- headers={"Content-Type": "application/json", **CORS_HEADERS},
129
- )
130
-
131
-
132
- def build_upstream_headers(origin: str, referer: str, priority: str,
133
- range_header: str | None,
134
- custom_headers: dict) -> dict:
135
- """
136
- Build a realistic browser-like header set.
137
- Order mirrors what Chrome 124 sends for media fetches.
138
- """
139
- headers: dict[str, str] = {}
140
-
141
- # Range must come first so CDNs that key on it see it early
142
- if range_header:
143
- headers["Range"] = range_header
144
-
145
- headers["Accept"] = "*/*"
146
- headers["Accept-Language"] = "en-US,en;q=0.9"
147
- # Let httpx handle Accept-Encoding automatically (it sets it to gzip/br
148
- # and decompresses transparently), but CDNs want to see it present.
149
- headers["Accept-Encoding"] = "gzip, deflate, br"
150
- headers["Origin"] = origin
151
- headers["Referer"] = referer
152
- headers["Priority"] = priority
153
- headers["Sec-Fetch-Dest"] = "empty"
154
- headers["Sec-Fetch-Mode"] = "cors"
155
- headers["Sec-Fetch-Site"] = "cross-site"
156
- headers["Sec-Ch-Ua"] = (
157
- '"Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99"'
158
- )
159
- headers["Sec-Ch-Ua-Mobile"] = "?1"
160
- headers["Sec-Ch-Ua-Platform"] = '"Android"'
161
- headers["User-Agent"] = (
162
- "Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36 "
163
- "(KHTML, like Gecko) Chrome/124.0.0.0 Mobile Safari/537.36"
164
- )
165
-
166
- # Custom headers override defaults but cannot set blocked headers
167
- for k, v in custom_headers.items():
168
- if k.lower() not in BLOCKED_UPSTREAM_HEADERS:
169
- headers[k] = v
170
-
171
- return headers
172
-
173
- # ---------------------------------------------------------------------------
174
- # Route
175
- # ---------------------------------------------------------------------------
176
-
177
- @app.api_route("/{path:path}", methods=["GET", "HEAD", "OPTIONS"])
178
- async def proxy(request: Request, path: str = ""):
179
- if request.method == "OPTIONS":
180
- return Response(status_code=204, headers=CORS_HEADERS)
181
-
182
- params = dict(request.query_params)
183
-
184
- target_url = params.get("url")
185
- if not target_url:
186
- return json_response({"error": "Missing url parameter"}, 400)
187
-
188
- try:
189
- parsed_target = urlparse(target_url)
190
- if not parsed_target.scheme or not parsed_target.netloc:
191
- raise ValueError("bad url")
192
- except Exception:
193
- return json_response({"error": "Invalid url parameter"}, 400)
194
-
195
- target_origin = f"{parsed_target.scheme}://{parsed_target.netloc}"
196
- origin = params.get("origin") or target_origin
197
- referer = params.get("referer") or f"{target_origin}/"
198
- priority = params.get("priority") or "u=1, i"
199
- raw_custom_headers = params.get("headers")
200
-
201
- custom_headers = parse_custom_headers(raw_custom_headers)
202
- if custom_headers is None:
203
- return json_response({"error": "Invalid headers parameter"}, 400)
204
-
205
- range_header = request.headers.get("range")
206
-
207
- upstream_headers = build_upstream_headers(
208
- origin, referer, priority, range_header, custom_headers
209
- )
210
-
211
- # httpx must NOT re-encode already-present Accept-Encoding;
212
- # disable its automatic decompression so we can stream raw bytes.
213
- async with httpx.AsyncClient(
214
- follow_redirects=True,
215
- headers={}, # no client-level defaults; we set everything per-request
216
- ) as client:
217
- upstream_resp = await client.request(
218
- method="GET",
219
- url=target_url,
220
- headers=upstream_headers,
221
- # Disable httpx transparent decompression so Content-Length stays valid
222
- extensions={"decode_content": False},
223
- )
224
-
225
- content_type = upstream_resp.headers.get("content-type", "")
226
- is_playlist = "mpegurl" in content_type or target_url.split("?")[0].endswith(".m3u8")
227
-
228
- # --- Error passthrough ---
229
- if upstream_resp.status_code not in range(200, 300) and upstream_resp.status_code != 206:
230
- resp_headers = copy_response_headers(upstream_resp.headers)
231
- resp_headers.update(CORS_HEADERS)
232
- return Response(
233
- content=upstream_resp.content,
234
- status_code=upstream_resp.status_code,
235
- headers=resp_headers,
236
- )
237
-
238
- # --- HLS playlist rewrite ---
239
- if is_playlist:
240
- base_request_url = str(request.base_url).rstrip("/")
241
- rewritten = rewrite_playlist(
242
- base_request_url,
243
- upstream_resp.text,
244
- str(upstream_resp.url),
245
- referer, origin, priority, raw_custom_headers,
246
- )
247
- resp_headers = copy_response_headers(
248
- upstream_resp.headers,
249
- {"Content-Type": "application/vnd.apple.mpegurl; charset=utf-8"},
250
- )
251
- resp_headers.update(CORS_HEADERS)
252
- # Recalculate Content-Length since we rewrote the body
253
- encoded = rewritten.encode("utf-8")
254
- resp_headers["Content-Length"] = str(len(encoded))
255
- return Response(
256
- content=encoded,
257
- status_code=upstream_resp.status_code,
258
- headers=resp_headers,
259
- )
260
-
261
- # --- Binary / segment passthrough ---
262
- resp_headers = copy_response_headers(upstream_resp.headers)
263
- resp_headers.update(CORS_HEADERS)
264
- return Response(
265
- content=upstream_resp.content,
266
- status_code=upstream_resp.status_code,
267
- headers=resp_headers,
268
- )