Hana Celeste commited on
Commit
027fe8d
·
verified ·
1 Parent(s): 40861f3

Update app/gscode_logic.py

Browse files
Files changed (1) hide show
  1. app/gscode_logic.py +39 -25
app/gscode_logic.py CHANGED
@@ -1,40 +1,54 @@
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
  }
 
1
  # gscode_logic.py
2
+ import aiohttp
3
  from bs4 import BeautifulSoup
 
4
 
5
+ GENSHIN_API = (
6
+ "https://genshin-impact.fandom.com/api.php"
7
+ "?action=parse"
8
+ "&page=Promotional_Code"
9
+ "&prop=text"
10
+ "&format=json"
11
+ )
12
 
13
+ class GenshinCodeLogic:
14
+ def __init__(self):
15
+ self.session: aiohttp.ClientSession | None = None
16
+
17
+ async def start(self):
18
+ if not self.session:
19
+ self.session = aiohttp.ClientSession()
20
+
21
+ async def stop(self):
22
+ if self.session:
23
+ await self.session.close()
24
+ self.session = None
25
+
26
+ async def fetch_codes(self):
27
+ async with self.session.get(
28
+ GENSHIN_API,
29
+ headers={
30
+ "User-Agent": "Mozilla/5.0"
31
+ },
32
+ timeout=aiohttp.ClientTimeout(total=20)
33
+ ) as resp:
34
+ if resp.status != 200:
35
+ return {"count": 0, "codes": []}
36
+
37
+ data = await resp.json()
38
 
 
39
  html = data.get("parse", {}).get("text", {}).get("*")
40
  if not html:
41
  return {"count": 0, "codes": []}
42
 
 
43
  soup = BeautifulSoup(html, "html.parser")
44
 
45
+ codes = {
46
+ c.text.strip()
47
+ for c in soup.select("code")
48
+ if c.text and len(c.text.strip()) >= 6
49
+ }
 
 
 
 
50
 
51
  return {
52
  "count": len(codes),
53
+ "codes": sorted(codes)
54
  }