-
Notifications
You must be signed in to change notification settings - Fork 0
/
MAA-Manager.py
297 lines (246 loc) · 9.06 KB
/
MAA-Manager.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
from flask import Flask, abort
from datetime import datetime, timedelta
from pathlib import Path
from dataclasses import dataclass
from sys import stderr
import traceback
import json
import signal
from smtplib import SMTP, SMTP_SSL
from email.message import EmailMessage
import requests
import time
import hmac
import hashlib
from apscheduler.schedulers.background import BackgroundScheduler
from random import randint
SAVED = Path("config/saved.json")
if SAVED.exists():
with SAVED.open() as file:
LAST_ACTION = json.load(file)
else:
LAST_ACTION = dict()
@dataclass
class MailSender:
host: str
port: int
ssl: bool
username: str
password: str
OFFLINE = "{} has just offline."
DAILY_ERROR = "{} has some trouble with daily sign-in."
def __post_init__(self):
self._msg = EmailMessage()
self._msg["From"] = self._msg["To"] = self.username
# check connection
self.smtp_server()
def smtp_server(self) -> SMTP | SMTP_SSL:
smtp = SMTP_SSL if self.ssl else SMTP
smtp_server = smtp(self.host, self.port)
smtp_server.login(self.username, self.password)
return smtp_server
def send_offline(self, user: str):
self._msg["Subject"] = "MAA-Manager Offline Notice"
self._msg.set_content(self.OFFLINE.format(user))
with self.smtp_server() as smtp_server:
smtp_server.send_message(self._msg)
def send_daily_error(self, user: str):
self._msg["Subject"] = "MAA-Manager Daily-Sign Error"
self._msg.set_content(self.DAILY_ERROR.format(user))
with self.smtp_server() as smtp_server:
smtp_server.send_message(self._msg)
class DailySignException(Exception):
pass
@dataclass
class DailySign:
phone: str
password: str
uid: str
HEADER = {
"User-Agent": "Skland/1.0.1 (com.hypergryph.skland; build:100001014; Android 31; ) Okhttp/4.11.0",
"Accept-Encoding": "gzip",
"Connection": "close",
}
LOGIN_URL = "https://as.hypergryph.com/user/auth/v1/token_by_phone_password"
GRANT_URL = "https://as.hypergryph.com/user/oauth2/v2/grant"
CRED_URL = "https://zonai.skland.com/api/v1/user/auth/generate_cred_by_code"
DAILY_URL = "https://zonai.skland.com/api/v1/game/attendance"
def __post_init__(self):
try:
hypergryph_token = requests.post(
self.LOGIN_URL,
json={
"phone": self.phone,
"password": self.password,
},
headers=self.HEADER,
).json()["data"]["token"]
except Exception as e:
raise DailySignException(
f"[{self.phone}]: Failed to get token of `ak.hypergryph.com`."
) from e
try:
grant_code = requests.post(
self.GRANT_URL,
json={
"appCode": "4ca99fa6b56cc2ba",
"token": hypergryph_token,
"type": 0,
},
headers=self.HEADER,
).json()["data"]["code"]
_ = requests.post(
self.CRED_URL,
json={
"kind": 1,
"code": grant_code,
},
headers=self.HEADER,
).json()["data"]
self.skland_cred = _["cred"]
self.skland_token = _["token"]
except Exception as e:
raise DailySignException(
f"[{self.phone}]: Failed to log into `skland.com`."
) from e
def __call__(self):
print(f"==========DailySign [{self.phone}] Started==========", file=stderr)
try:
# It was said that `- 2` should be added according to experience.
timestamp = str(time.time() - 2)
# It was said that it's fine for all fields (other than timestamp) to be empty.
header = {
"platform": "",
"dId": "",
"vName": "",
"timestamp": timestamp,
}
payload = {
"uid": self.uid,
"gameId": 1,
}
content = "".join(
[self.DAILY_URL, timestamp, json.dumps(header, separators=(",", ":"))]
)
encrypted = (
hmac.new(self.skland_token.encode(), content.encode(), hashlib.sha256)
.hexdigest()
.encode()
)
# It was said that the signature is needed, but it still worked without it.
# So I left it `assigned but never used`, intentionally (for future use).
signature = hashlib.md5(encrypted).hexdigest()
awards = requests.post(
self.DAILY_URL,
json=payload,
headers={"cred": self.skland_cred, "sign": signature}
| self.HEADER
| header,
).json()["data"]["awards"]
for award in awards:
print(
f"Award: {award['resource']['name']} × {award.get('count', 1)}",
file=stderr,
)
except Exception:
MAIL_SENDER.send_daily_error(self.phone)
print("==========DailySign Sign Failed==========", file=stderr)
traceback.print_exc()
print("==========DailySign Sign Failed==========", file=stderr)
finally:
print(f"==========DailySign [{self.phone}] Ended==========", file=stderr)
CONFIG = Path("config/config.json")
MAIL_SENDER: MailSender | None
if CONFIG.exists():
try:
with CONFIG.open() as file:
config = json.load(file)
mail = config["mail-sender"]
MAIL_SENDER = MailSender(
host=mail["host"],
port=mail.get("port", 0),
ssl=mail.get("ssl", False),
username=mail["username"],
password=mail["password"],
)
SCHEDULER = BackgroundScheduler()
for daily_config in config.get("daily-sign", []):
try:
daily_sign = DailySign(
phone=daily_config["phone"],
password=daily_config["password"],
uid=daily_config["uid"],
)
hour = randint(0, 8)
minute = randint(0, 59)
second = randint(0, 59)
print(
f"[{daily_sign.phone}]: Schedule daily sign at {hour:02}:{minute:02}:{second:02}.",
file=stderr,
)
SCHEDULER.add_job(
daily_sign,
trigger="cron",
hour=hour,
minute=minute,
second=second,
)
except DailySignException: # error with DailySign auth
print("==========DailySign Auth Failed==========", file=stderr)
traceback.print_exc()
print("==========DailySign Auth Failed==========", file=stderr)
if SCHEDULER.get_jobs():
SCHEDULER.start()
except Exception: # other fatal error
MAIL_SENDER = None
print("==========ERROR READING CONFIG==========", file=stderr)
traceback.print_exc()
print("==========ERROR READING CONFIG==========", file=stderr)
WAITING_MAIL = set()
def sigterm_handler(signalnum, frame):
"""Save `LAST_ACCESS` before exit."""
with SAVED.open("w") as file:
json.dump(LAST_ACTION, file)
exit(0)
# register SIGTERM handler
signal.signal(signal.SIGTERM, sigterm_handler)
app = Flask(__name__)
def display(duration: timedelta) -> str:
"""Display`timedelta` with a better format."""
def format(amount: int, unit: str):
return f"{amount} {unit}" + ("s " if abs(amount) != 1 else " ")
msg = ""
if duration.days:
msg += format(duration.days, "day")
hour = duration.seconds // 3600
if hour:
msg += format(hour, "hour")
elif msg: # implies hour is 0
msg += "0 hours "
minute = duration.seconds % 3600 // 60
if minute:
msg += format(minute, "minute")
elif msg: # implies minute is 0
msg += "0 minutes "
second = duration.seconds % 60
msg += format(second, "second")
return msg
@app.route("/query/<user>")
def query(user):
if _ := LAST_ACTION.get(user):
action, time = _
if action == "online":
WAITING_MAIL.add(user)
duration = datetime.now() - datetime.fromisoformat(time)
return f"MAA last {action} {display(duration)}ago.\n"
else:
return "MAA has no action since the server started.\n"
@app.route("/report/<user>/<action>")
def report(user, action):
if action not in ("online", "offline"):
abort(404)
if action == "offline" and user in WAITING_MAIL:
MAIL_SENDER.send_offline(user)
WAITING_MAIL.remove(user)
LAST_ACTION[user] = (action, str(datetime.now()))
return ""