Spaces:
Sleeping

veltrixcode commited on
Commit
4d3c484
·
verified ·
1 Parent(s): 5cc8123

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +78 -56
main.py CHANGED
@@ -1,10 +1,9 @@
1
  import json
2
  import re
3
- from urllib.parse import urljoin, urlparse, urlencode, parse_qs, urlunparse
4
 
5
  import httpx
6
  from fastapi import FastAPI, Request, Response
7
- from fastapi.responses import StreamingResponse
8
 
9
  app = FastAPI(title="HLS Media Proxy")
10
 
@@ -28,14 +27,15 @@ BLOCKED_UPSTREAM_HEADERS = {
28
  "content-length",
29
  "host",
30
  "range",
 
 
 
 
 
31
  }
32
 
33
  HEADER_NAME_RE = re.compile(r"^[A-Za-z0-9-]+$")
34
 
35
- # ---------------------------------------------------------------------------
36
- # CORS
37
- # ---------------------------------------------------------------------------
38
-
39
  CORS_HEADERS = {
40
  "Access-Control-Allow-Origin": "*",
41
  "Access-Control-Allow-Methods": "GET, HEAD, OPTIONS",
@@ -55,10 +55,8 @@ def parse_custom_headers(raw: str | None) -> dict | None:
55
  parsed = json.loads(raw)
56
  except (json.JSONDecodeError, ValueError):
57
  return None
58
-
59
  if not isinstance(parsed, dict):
60
  return None
61
-
62
  safe = {}
63
  for name, value in parsed.items():
64
  if not HEADER_NAME_RE.match(name):
@@ -68,7 +66,6 @@ def parse_custom_headers(raw: str | None) -> dict | None:
68
  if not isinstance(value, str):
69
  continue
70
  safe[name] = value
71
-
72
  return safe
73
 
74
 
@@ -84,7 +81,6 @@ def build_proxy_url(base_url: str, target_url: str, referer: str, origin: str,
84
  params["priority"] = priority
85
  if custom_headers:
86
  params["headers"] = custom_headers
87
-
88
  return urlunparse(parsed._replace(query=urlencode(params)))
89
 
90
 
@@ -98,13 +94,11 @@ def rewrite_playlist(base_request_url: str, playlist: str, upstream_url: str,
98
  resolved = urljoin(upstream_url, value)
99
  return build_proxy_url(base_request_url, resolved, referer, origin, priority, custom_headers)
100
 
101
- # Rewrite URI="..." attributes
102
  def replace_uri(m: re.Match) -> str:
103
  return f'URI="{rewrite_entry(m.group(1))}"'
104
 
105
  result = re.sub(r'URI="([^"]+)"', replace_uri, playlist)
106
 
107
- # Rewrite bare segment lines
108
  lines = []
109
  for line in result.split("\n"):
110
  trimmed = line.strip()
@@ -112,23 +106,18 @@ def rewrite_playlist(base_request_url: str, playlist: str, upstream_url: str,
112
  lines.append(line)
113
  else:
114
  lines.append(rewrite_entry(trimmed))
115
-
116
  return "\n".join(lines)
117
 
118
 
119
- def copy_response_headers(source_headers: httpx.Headers, overrides: dict | None = None) -> dict:
120
  headers: dict[str, str] = {}
121
-
122
  for name in FORWARDED_RESPONSE_HEADERS:
123
- value = source_headers.get(name)
124
  if value:
125
  headers[name] = value
126
-
127
  if overrides:
128
  headers.update(overrides)
129
-
130
- headers["Cache-Control"] = source_headers.get("cache-control", "public, max-age=300")
131
-
132
  return headers
133
 
134
 
@@ -139,13 +128,54 @@ def json_response(data: dict, status: int = 200) -> Response:
139
  headers={"Content-Type": "application/json", **CORS_HEADERS},
140
  )
141
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
  # ---------------------------------------------------------------------------
143
  # Route
144
  # ---------------------------------------------------------------------------
145
 
146
  @app.api_route("/{path:path}", methods=["GET", "HEAD", "OPTIONS"])
147
  async def proxy(request: Request, path: str = ""):
148
- # CORS preflight
149
  if request.method == "OPTIONS":
150
  return Response(status_code=204, headers=CORS_HEADERS)
151
 
@@ -158,13 +188,13 @@ async def proxy(request: Request, path: str = ""):
158
  try:
159
  parsed_target = urlparse(target_url)
160
  if not parsed_target.scheme or not parsed_target.netloc:
161
- raise ValueError
162
- except (ValueError, Exception):
163
  return json_response({"error": "Invalid url parameter"}, 400)
164
 
165
  target_origin = f"{parsed_target.scheme}://{parsed_target.netloc}"
166
- origin = params.get("origin") or target_origin
167
- referer = params.get("referer") or f"{target_origin}/"
168
  priority = params.get("priority") or "u=1, i"
169
  raw_custom_headers = params.get("headers")
170
 
@@ -172,33 +202,31 @@ async def proxy(request: Request, path: str = ""):
172
  if custom_headers is None:
173
  return json_response({"error": "Invalid headers parameter"}, 400)
174
 
175
- upstream_headers = {
176
- "Accept": "*/*",
177
- "Origin": origin,
178
- "Referer": referer,
179
- "Priority": priority,
180
- "User-Agent": (
181
- "Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36 "
182
- "(KHTML, like Gecko) Chrome/144.0.0.0 Mobile Safari/537.36"
183
- ),
184
- }
185
- upstream_headers.update(custom_headers)
186
-
187
  range_header = request.headers.get("range")
188
- if range_header:
189
- upstream_headers["Range"] = range_header
190
 
191
- async with httpx.AsyncClient(follow_redirects=True) as client:
 
 
 
 
 
 
 
 
 
192
  upstream_resp = await client.request(
193
  method="GET",
194
  url=target_url,
195
  headers=upstream_headers,
 
 
196
  )
197
 
198
  content_type = upstream_resp.headers.get("content-type", "")
199
- is_playlist = "mpegurl" in content_type or target_url.endswith(".m3u8")
200
 
201
- if not upstream_resp.is_success and upstream_resp.status_code not in (206,):
 
202
  resp_headers = copy_response_headers(upstream_resp.headers)
203
  resp_headers.update(CORS_HEADERS)
204
  return Response(
@@ -207,38 +235,32 @@ async def proxy(request: Request, path: str = ""):
207
  headers=resp_headers,
208
  )
209
 
 
210
  if is_playlist:
211
- playlist_text = upstream_resp.text
212
-
213
- # base_request_url should preserve scheme+host of our own proxy
214
  base_request_url = str(request.base_url).rstrip("/")
215
-
216
  rewritten = rewrite_playlist(
217
  base_request_url,
218
- playlist_text,
219
  str(upstream_resp.url),
220
- referer,
221
- origin,
222
- priority,
223
- raw_custom_headers,
224
  )
225
-
226
  resp_headers = copy_response_headers(
227
  upstream_resp.headers,
228
  {"Content-Type": "application/vnd.apple.mpegurl; charset=utf-8"},
229
  )
230
  resp_headers.update(CORS_HEADERS)
231
-
 
 
232
  return Response(
233
- content=rewritten.encode("utf-8"),
234
  status_code=upstream_resp.status_code,
235
  headers=resp_headers,
236
  )
237
 
238
- # Binary / segment passthrough
239
  resp_headers = copy_response_headers(upstream_resp.headers)
240
  resp_headers.update(CORS_HEADERS)
241
-
242
  return Response(
243
  content=upstream_resp.content,
244
  status_code=upstream_resp.status_code,
 
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
 
 
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",
 
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):
 
66
  if not isinstance(value, str):
67
  continue
68
  safe[name] = value
 
69
  return safe
70
 
71
 
 
81
  params["priority"] = priority
82
  if custom_headers:
83
  params["headers"] = custom_headers
 
84
  return urlunparse(parsed._replace(query=urlencode(params)))
85
 
86
 
 
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()
 
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
 
 
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
 
 
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
 
 
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(
 
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,