-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgenerate.py
310 lines (271 loc) · 9.41 KB
/
generate.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
# -*- coding: utf-8 -*-
import argparse
import hashlib
import math
import os
import random
import time
import requests
from selenium import webdriver
from selenium.webdriver.common.by import By
from PIL import Image, ImageDraw
MIYOUSHE_API = 0
HOYOLAB_API = 1
DS_SALT = "xV8v4Qu54lUKrEYFZkJhB8cuOh9Asafs"
REGION_CN_OFFICIAL = "cn_gf01"
REGION_CN_BILIBILI = "cn_qd01"
REGION_OS_NA = "os_usa"
REGION_OS_EU = "os_euro"
REGION_OS_AS = "os_asia"
REGION_OS_SAR = "os_cht"
APIS = [
{
"PlayerIndexUrl": "https://api-takumi-record.mihoyo.com/game_record/app/genshin/api/index",
"PlayerCharacterUrl": "https://api-takumi-record.mihoyo.com/game_record/app/genshin/api/character",
"PlayerSprialAbyssUrl": "https://api-takumi-record.mihoyo.com/game_record/app/genshin/api/spiralAbyss",
},
{
"PlayerIndexUrl": "https://bbs-api-os.hoyolab.com/game_record/genshin/api/index",
"PlayerCharacterUrl": "", # Not supported
"PlayerSprialAbyssUrl": "https://bbs-api-os.hoyolab.com/game_record/genshin/api/spiralAbyss",
},
]
with open("template.html", "r", encoding="utf-8") as f:
HTML_TEMPLATE = f.read()
global_config = {"cookie": ""}
def get_region_by_uid(uid):
if len(uid) < 2:
return None
c = uid[:1]
if c == "1" or c == "2":
return REGION_CN_OFFICIAL
elif c == "5":
return REGION_CN_BILIBILI
elif c == "6":
return REGION_OS_NA
elif c == "7":
return REGION_OS_EU
elif c == "8":
return REGION_OS_AS
elif c == "9":
return REGION_OS_SAR
return None
def get_apis_by_region(region):
if len(region) < 2:
return None
if region[:2] == "cn":
return APIS[MIYOUSHE_API]
elif region[:2] == "os":
return APIS[HOYOLAB_API]
return None
def get_random_background():
backgrounds = []
for file in os.listdir("./assets/img"):
if file.endswith(".jpg") or file.endswith(".png"):
backgrounds.append(file)
if len(backgrounds) == 0:
raise Exception("No backgrounds found")
return "assets/img/" + random.choice(backgrounds)
def render_html(fn):
driver = webdriver.ChromiumEdge()
driver.get(f"file:///{os.getcwd()}/{fn}")
driver.set_window_size(1000, 1000)
time.sleep(2)
driver.find_element(By.ID, "card").screenshot(fn.replace(".html", ".png"))
# png = driver.get_screenshot_as_png()
driver.quit()
# with open(fn.replace(".html", ".png"), "wb") as f:
# f.write(png)
process_png(fn.replace(".html", ".png"))
def is_in_square(x, y, sx, sy, l):
"""
(x, y) is the point to check
(sx, sy) is the top left corn
l is the length of the square
"""
return x >= sx and x <= sx + l and y >= sy and y <= sy + l
def is_in_rect(x, y, sx, sy, w, h):
"""
(x, y) is the point to check
(sx, sy) is the top left corn
w is the width of the rect
h is the height of the rect
"""
return x >= sx and x <= sx + w and y >= sy and y <= sy + h
def is_in_circle(x, y, cx, cy, radius):
"""
(x, y) is the point to check
(cx, cy) is the center of the circle
radius is the radius of the circle
"""
return (x - cx) ** 2 + (y - cy) ** 2 < radius ** 2
def is_in_rounded_rect(x, y):
WIDTH = 720
HEIGHT = 420
RADIUS = 40
CIRCLE_CENTERS = [
(0 + RADIUS, 0 + RADIUS),
(WIDTH - RADIUS, 0 + RADIUS),
(0 + RADIUS, HEIGHT - RADIUS),
(WIDTH - RADIUS, HEIGHT - RADIUS),
]
SQUARE_CORNERS = [
(0, 0),
(WIDTH - RADIUS, 0),
(0, HEIGHT - RADIUS),
(WIDTH - RADIUS, HEIGHT - RADIUS),
]
if x >= WIDTH or y >= HEIGHT:
return False
if x >= RADIUS and x <= WIDTH - RADIUS and y >= RADIUS and y <= HEIGHT - RADIUS:
return True
outside_squares = True
for i in range(0, 4):
corner = SQUARE_CORNERS[i]
center = CIRCLE_CENTERS[i]
if is_in_square(x, y, corner[0], corner[1], RADIUS):
if is_in_circle(x, y, center[0], center[1], RADIUS):
return True
outside_squares = False
if outside_squares:
return True
return False
def process_png(fn):
img = Image.open(fn)
img = img.convert("RGBA")
pixels = img.load()
for x in range(img.size[0]):
for y in range(img.size[1]):
if not is_in_rounded_rect(x, y):
r, g, b = pixels[x, y][:3]
# convert white to transparent
if r > 240 and g > 240 and b > 240:
pixels[x, y] = (255, 255, 255, 0)
# convert grey to transparent gradient
elif r == g and g == b:
pixels[x, y] = (r, g, b, 255 - r)
img.save("out.png")
img.close()
os.remove(fn)
def generate_ds(uid, region):
query = f"role_id={uid}&server={region}"
# Current time in seconds
t = int(time.time())
r = random.randint(100_000, 200_000)
if r == 100_000:
r = 642367
# Generate DS
text = f"salt={DS_SALT}&t={t}&r={r}&b=&q={query}"
sign = hashlib.md5(text.encode("utf-8")).hexdigest()
return f"{t},{r},{sign}"
def http_get(url, ds):
headers = {
"Referer": "https://webstatic.mihoyo.com/",
"User-Agent": "Mozilla/5.0 (Linux; Android 13; M2101K9C Build/TKQ1.220829.002; wv) AppleWebKit/537.36 (KHTML, "
"like Gecko) Version/4.0 Chrome/108.0.5359.128 Mobile Safari/537.36 miHoYoBBS/2.44.1",
"X-Requested-With": "com.mihoyo.hyperion",
"DS": ds,
"Origin": "https://api-takumi-record.mihoyo.com",
"Host": "api-takumi-record.mihoyo.com",
"x-rpc-app_version": "2.44.1",
"x-rpc-client_type": "5",
"Cookie": global_config["cookie"],
}
return requests.get(url, headers=headers, timeout=10)
def get_player_index(uid, region):
apis = get_apis_by_region(region)
if apis is None:
raise Exception("Failed to get apis")
ds = generate_ds(uid, region)
url = apis["PlayerIndexUrl"] + f"?role_id={uid}&server={region}"
resp = http_get(url, ds)
if resp.status_code != 200:
resp.raise_for_status()
# print(resp.text)
return resp.json()
def generate_image(uid, region):
data = get_player_index(uid, region)
if data is None:
raise Exception("Failed to get player index")
if data["retcode"] != 0:
raise Exception(f"Failed to get player index: {data['message']}")
data = data["data"]
if data is None:
raise Exception("Bad player index data")
role_data = data["role"]
if role_data is None:
raise Exception("Bad player index data")
stats_data = data["stats"]
if stats_data is None:
raise Exception("Bad player index data")
home_list = data["homes"]
if home_list is None or type(home_list) != list:
raise Exception("Bad player index data")
name = role_data["nickname"]
level = role_data["level"]
"""
ActiveDayNumber int `json:"active_day_number"`
AchievementNumber int `json:"achievement_number"`
AnemoculusNumber int `json:"anemoculus_number"`
GeoculusNumber int `json:"geoculus_number"`
AvatarNumber int `json:"avatar_number"`
WayPointNumber int `json:"way_point_number"`
DomainNumber int `json:"domain_number"`
SpiralAbyss string `json:"spiral_abyss"`
PreciousChestNumber int `json:"precious_chest_number"`
LuxuriousChestNumber int `json:"luxurious_chest_number"`
ExquisiteChestNumber int `json:"exquisite_chest_number"`
CommonChestNumber int `json:"common_chest_number"`
ElectroculusNumber int `json:"electroculus_number"`
MagicChestNumber int `json:"magic_chest_number"`
DendroculusNumber int `json:"dendroculus_number"`
"""
active_days = stats_data["active_day_number"]
spiral_abyss = stats_data["spiral_abyss"]
achievements = stats_data["achievement_number"]
characters = stats_data["avatar_number"]
chests = (
stats_data["precious_chest_number"]
+ stats_data["luxurious_chest_number"]
+ stats_data["exquisite_chest_number"]
+ stats_data["common_chest_number"]
)
culus = (
stats_data["anemoculus_number"]
+ stats_data["geoculus_number"]
+ stats_data["electroculus_number"]
+ stats_data["dendroculus_number"]
)
waypoints = stats_data["way_point_number"]
comfort_num = 0
for home in home_list:
comfort_num = max(comfort_num, home["comfort_num"])
html = HTML_TEMPLATE.format(
background=get_random_background(),
name=name,
level=level,
uid=uid,
active_days=active_days,
spiral_abyss=spiral_abyss,
achievements=achievements,
characters=characters,
chests=chests,
culus=culus,
waypoints=waypoints,
comfort_num=comfort_num,
)
# print(html)
with open("temp.html", "w", encoding="utf-8") as f:
f.write(html)
render_html("temp.html")
os.remove("temp.html")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--uid", help="User ID", required=True)
parser.add_argument("--cookie", help="Cookie", required=True)
args = parser.parse_args()
global_config["cookie"] = args.cookie
region = get_region_by_uid(args.uid)
if region is None:
raise Exception("Failed to get region")
generate_image(args.uid, region)