Hana Celeste commited on
Commit
ae96995
·
verified ·
1 Parent(s): 6b3ac63

Rename app/gscode_logic.py to app/Gscode_logic.py

Browse files
Files changed (2) hide show
  1. app/Gscode_logic.py +40 -0
  2. app/gscode_logic.py +0 -40
app/Gscode_logic.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # gscode_logic.py
2
+ import json
3
+ from bs4 import BeautifulSoup
4
+ from fastapi import HTTPException
5
+
6
+ class GenshinCodeLogic:
7
+ async def fetch_codes(self, fetcher, url: str):
8
+ # 1. fetch raw
9
+ res = await fetcher.fetch(url)
10
+
11
+ if not res or "text" not in res:
12
+ raise HTTPException(500, "Fetch failed")
13
+
14
+ try:
15
+ data = json.loads(res["text"])
16
+ except Exception:
17
+ raise HTTPException(400, "Invalid JSON response")
18
+
19
+ # 2. lấy HTML string
20
+ html = data.get("parse", {}).get("text", {}).get("*")
21
+ if not html:
22
+ return {"count": 0, "codes": []}
23
+
24
+ # 3. parse HTML
25
+ soup = BeautifulSoup(html, "html.parser")
26
+
27
+ # 4. lấy <code>
28
+ codes = []
29
+ for c in soup.find_all("code"):
30
+ val = c.get_text(strip=True)
31
+ if val and len(val) >= 6:
32
+ codes.append(val)
33
+
34
+ # 5. unique + sort
35
+ codes = sorted(set(codes))
36
+
37
+ return {
38
+ "count": len(codes),
39
+ "codes": codes
40
+ }
app/gscode_logic.py DELETED
@@ -1,40 +0,0 @@
1
- # gscode_logic.py
2
- import httpx
3
- import re
4
- from html import unescape
5
-
6
- class GscodeApp:
7
- def __init__(self):
8
- self.client: httpx.AsyncClient | None = None
9
-
10
- async def start(self):
11
- self.client = httpx.AsyncClient(
12
- timeout=15,
13
- headers={
14
- "User-Agent": "HF-Gscode-API"
15
- }
16
- )
17
-
18
- async def stop(self):
19
- if self.client:
20
- await self.client.aclose()
21
-
22
- async def fetch_codes(self, url: str):
23
- if not self.client:
24
- raise RuntimeError("GscodeApp not started")
25
-
26
- resp = await self.client.get(url)
27
- resp.raise_for_status()
28
-
29
- text = resp.text
30
-
31
- text = unescape(text)
32
-
33
- codes = re.findall(r"<code>(.*?)</code>", text, re.I)
34
-
35
- codes = list(dict.fromkeys(c.strip() for c in codes if c.strip()))
36
-
37
- return {
38
- "count": len(codes),
39
- "codes": codes
40
- }