forked from zycn0910/Sign-ZXJY
/
process.py
476 lines (434 loc) · 19.9 KB
/
process.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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
import datetime
import hashlib
import hmac
import json
import logging
import os
import random
import re
import time
import requests
import tqdm
from bs4 import BeautifulSoup
import config
from utils import MessagePush
if config.log_report:
log_file_Name = f"职教家园-{datetime.datetime.now().strftime('%Y-%m-%d %H')}.log"
if not os.path.exists("log"):
os.mkdir("log")
else:
pass
open(f"log/{log_file_Name}", "a")
logging.getLogger('DEBUG')
logging.basicConfig(level=logging.NOTSET,
filename=f"log/{log_file_Name}",
filemode="a",
format="%(asctime)s - %(name)s - %(levelname)-s - %(message)s - %(filename)s - %(funcName)s - %(lineno)s",
datefmt="%Y-%m-%d %H:%M:%S",
encoding="utf-8"
)
else:
pass
def get_proxy():
headers = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36'
}
page = 1
while True:
try:
url = f"https://www.kuaidaili.com/free/inha/{page}/"
html = requests.get(url, headers=headers, timeout=3).text
page = page + 1
except Exception as e:
return None
soup = BeautifulSoup(html, features="lxml")
tr_tags = soup.find_all("tr")
proxy_list = []
for tr in tr_tags:
ip_tag = tr.find('td', {'data-title': 'IP'})
port_tag = tr.find('td', {'data-title': 'PORT'})
if ip_tag and port_tag:
ip = ip_tag.text
port = port_tag.text
proxy_list.append(ip + ":" + port)
for i in proxy_list:
if check_proxy_alive(i):
return i
else:
continue
def check_proxy_alive(proxy):
try:
response = requests.get('http://www.baidu.com/',
proxies={'http': 'http://' + proxy, 'https': 'https://' + proxy}, timeout=5)
if response.status_code == 200:
return True
else:
return False
except Exception as e:
return False
if config.proxy_enable:
print("代理已开启,正在获取代理地址。。。")
proxy_data = get_proxy()
logging.info(proxy_data)
print(f"本次运行使用代理 \033[31m{proxy_data}\033[0m")
else:
proxy_data = None
def random_Time(time):
data = random.randint(int(time[0]), int(time[1]))
logging.info(data)
return data
def get_Apitoken():
url = "http://sxbaapp.zcj.jyt.henan.gov.cn/api/getApitoken.ashx"
headers = {
'content-type': 'application/json;charset=UTF-8',
}
response = requests.post(url, headers=headers)
try:
result = response.json()
if result["code"] == 1001:
token = result["data"]["apitoken"]
logging.info(token)
return token
else:
logging.info("get_Apitoken获取token失败")
return ""
except Exception as e:
logging.info(e)
return ""
def load_users_from_json(file_path):
if os.path.exists(file_path):
logging.info("检测到用户数据文件,已加载!")
else:
open(file_path, 'w', encoding='utf-8').write("[\n\n]")
logging.info(f"未检测到 {file_path} 文件,已自动创建!")
return json.load(open(file_path, 'r', encoding='utf-8'))
def calculate_hmac_sha256(secret_key, message):
key = bytes(secret_key, 'utf-8')
message = bytes(message, 'utf-8')
hashed = hmac.new(key, message, hashlib.sha256)
logging.info(hashed)
return hashed.hexdigest()
def generate_headers(sign, phonetype, token, timestamp):
if "iph" in phonetype.lower():
os = "ios"
Accept = "*/*"
Version = "".join(re.findall('new__latest__version">(.*?)</p>',
requests.get(
'https://apps.apple.com/us/app/%E8%81%8C%E6%A0%A1%E5%AE%B6%E5%9B%AD/id1606842290').text,
re.S)).replace('Version ', '')
Accept_Encoding = 'gzip, deflate, br'
Accept_Language = 'zh-Hans-CN;q=1'
Content_Type = 'application/json'
User_Agent = "Internship/1.3.8 (iPhone; iOS 16.6; Scale/3.00)"
Connection = "keep-alive"
else:
os = "android"
Accept = "*/*"
Version = "".join(re.findall('v\d+\.\d+\.\d+',
requests.get(
'https://r.app.xiaomi.com/details?id=com.wyl.exam').text,
re.S)).replace('v', '')
Accept_Encoding = 'gzip'
Accept_Language = 'zh-Hans-CN;q=1'
Content_Type = 'application/json; charset=UTF-8'
User_Agent = "okhttp/3.14.9"
Connection = "keep-alive"
data = {
'Accept': Accept,
'timestamp': timestamp,
'os': os,
'Accept-Encoding': Accept_Encoding,
'Accept-Language': Accept_Language,
'Content-Type': Content_Type,
'User-Agent': User_Agent,
'Connection': Connection,
'phone': phonetype,
'token': token,
'sign': sign,
'appVersion': Version
}
logging.info(data)
return data
def send_request(url, method, headers, data, proxy=None):
global proxy_data
if proxy is not None:
if method.upper() == 'POST':
if check_proxy_alive(proxy):
response = requests.post(url=url, headers=headers, data=json.dumps(data),
proxies={'http': 'http://' + proxy, 'https': 'https://' + proxy},
timeout=5)
else:
tqdm.tqdm.write(f"\033[31m原代理已失效\033[0m")
tqdm.tqdm.write(f"\033[33m本次提交将不使用代理\033[0m")
response = requests.post(url=url, headers=headers, data=json.dumps(data))
proxy_data = get_proxy()
tqdm.tqdm.write(f"现用代理改为 \033[32m{proxy_data}\033[0m")
logging.info(proxy)
logging.info(response)
return response.text
elif method.upper() == 'GET':
if check_proxy_alive(proxy):
response = requests.get(url, headers=headers, params=data,
proxies={'http': 'http://' + proxy, 'https': 'https://' + proxy},
timeout=5)
else:
tqdm.tqdm.write(f"\033[31m原代理已失效\033[0m")
tqdm.tqdm.write(f"\033[33m本次提交将不使用代理\033[0m")
response = requests.get(url=url, headers=headers, data=json.dumps(data))
proxy_data = get_proxy()
tqdm.tqdm.write(f"现用代理改为 \033[32m{proxy_data}\033[0m")
logging.info(proxy)
logging.info(response)
return response.text
else:
raise ValueError("Unsupported HTTP method")
else:
if method.upper() == 'POST':
response = requests.post(url=url, headers=headers, data=json.dumps(data))
return response.text
elif method.upper() == 'GET':
response = requests.get(url=url, headers=headers, data=json.dumps(data))
return response.text
else:
raise ValueError("Unsupported HTTP method")
def calculate_sign(data, token):
json_data = json.dumps(data)
combined_text = json_data + token
data = calculate_hmac_sha256('Anything_2023', combined_text)
logging.info(data)
return data
def login_request(phone_type, phone_number, password, additional_text=None, data=None):
if data is None:
data = {
"phone": phone_number,
"password": hashlib.md5(password.encode()).hexdigest(),
"dtype": 6,
}
sign = calculate_sign(data, additional_text)
headers = generate_headers(sign, phone_type, additional_text, str(round(time.time() * 1000)))
url = 'http://sxbaapp.zcj.jyt.henan.gov.cn/api/relog.ashx'
response_text = send_request(url=url, method='POST', headers=headers, data=data, proxy=proxy_data)
logging.info(response_text)
return response_text
def sign_in_request(uid, address, phonetype, probability, longitude, latitude, additional_text,
modify_coordinates=False):
longitude = float(longitude)
latitude = float(latitude)
if modify_coordinates:
longitude = round(longitude + random.uniform(-0.00001, 0.00001), 6)
latitude = round(latitude + random.uniform(-0.00001, 0.00001), 6)
data = {
"dtype": 1,
"uid": uid,
"address": address,
"phonetype": phonetype,
"probability": probability,
"longitude": longitude,
"latitude": latitude
}
sign = calculate_sign(data, additional_text)
header = generate_headers(sign, phonetype, additional_text, str(round(time.time() * 1000)))
url = 'http://sxbaapp.zcj.jyt.henan.gov.cn/api/clockindaily20220827.ashx'
response_text = send_request(url=url, method='POST', headers=header, data=data, proxy=proxy_data)
logging.info(response_text)
return response_text
def get_user_uid(deviceId, phone, password):
login_token = get_Apitoken()
if not login_token:
print("获取 Token 失败,无法继续操作")
login_data = login_request(deviceId, phone, password, login_token)
logging.info(login_data)
return login_data
def get_account_data(deviceId, phone, password):
user_data = json.loads(get_user_uid(deviceId, phone, password))
uid = user_data['data']['uid']
data = {
"dtype": 2,
"uid": uid
}
login_data = login_request(deviceId, phone, password, user_data['data']['UserToken'], data)
logging.info(login_data)
return login_data
def login_and_sign_in(user, endday):
title = "职教家园打卡失败!"
login_feedback = "登录失败!"
push_feedback = "推送无效!"
# 登录
if not user['enabled']:
content = f"未启用打卡,即将跳过!"
data = login_feedback, content, push_feedback
logging.info(data)
return data
if endday >= 0:
pass
else:
title = "职教家园打卡通知"
content = f"您已到期!"
push_feedback = MessagePush.pushMessage(addinfo=True, pushmode=user["pushmode"], pushdata=user['pushdata'],
title=title, content=content)
data = login_feedback, content, push_feedback
logging.info(data)
return data
login_data = get_user_uid(user['deviceId'], user['phone'], user['password'])
try:
login_result = json.loads(login_data)
if login_result['code'] == 1001:
login_feedback = f"{user['name']} 登录成功!"
uid = login_result['data']['uid']
global ADDITIONAL_TEXT
ADDITIONAL_TEXT = login_result['data']['UserToken']
if not ADDITIONAL_TEXT:
print("获取 Token 失败,无法继续操作")
sign_in_response = sign_in_request(uid, user['address'], user['deviceId'], 0, user['longitude'],
user['latitude'], ADDITIONAL_TEXT,
user['modify_coordinates'])
logging.info(sign_in_response)
try:
sign_in_result = json.loads(sign_in_response)
if sign_in_result['code'] == 1001:
title = "职教家园打卡成功!"
content = f"打卡成功,提示信息:" + sign_in_result['msg']
if config.day_report or config.week_report or config.month_report:
content = content + f"\n实习报告提交:{report_handler(user)}" + f"\n剩余时间:{endday}天"
push_feedback = MessagePush.pushMessage(addinfo=False, pushmode=user["pushmode"],
pushdata=user['pushdata'], title=title, content=content, )
logging.info(f"{login_feedback}, {content}, {push_feedback}")
return login_feedback, content, push_feedback
else:
content = f"打卡失败,错误信息:" + sign_in_result.get('msg',
'未知错误') + f"\n剩余时间:{endday}天"
push_feedback = MessagePush.pushMessage(addinfo=False, pushmode=user["pushmode"],
pushdata=user['pushdata'], title=title, content=content)
logging.info(f"{login_feedback}, {content}, {push_feedback}")
return login_feedback, content, push_feedback
except json.JSONDecodeError:
content = f"处理打卡响应时发生 JSON 解析错误" + f"\n剩余时间:{endday}天"
push_feedback = MessagePush.pushMessage(addinfo=False, pushmode=user["pushmode"],
pushdata=user['pushdata'], title=title, content=content)
logging.info(f"{login_feedback}, {content}, {push_feedback}")
return login_feedback, content, push_feedback
else:
content = f"登录失败,错误信息:" + login_result.get('msg', '未知错误') + f"\n剩余时间:{endday}天"
push_feedback = MessagePush.pushMessage(addinfo=False, pushmode=user["pushmode"], pushdata=user['pushdata'],
title=title, content=content)
logging.info(f"{login_feedback}, {content}, {push_feedback}")
return login_feedback, content, push_feedback
except json.JSONDecodeError:
content = f"处理登录响应时发生 JSON 解析错误" + f"\n剩余时间:{endday}天"
push_feedback = MessagePush.pushMessage(addinfo=False, pushmode=user["pushmode"], pushdata=user['pushdata'],
title=title, content=content)
logging.info(f"{login_feedback}, {content}, {push_feedback}")
return login_feedback, content, push_feedback
except KeyError:
content = f"处理登录响应时发生关键字错误" + f"\n剩余时间:{endday}天"
push_feedback = MessagePush.pushMessage(addinfo=False, pushmode=user["pushmode"], pushdata=user['pushdata'],
title=title, content=content)
logging.info(content)
return login_feedback, content, push_feedback
def day_Report(time, user, uid, summary, record, project):
url = "http://sxbaapp.zcj.jyt.henan.gov.cn/api/ReportHandler.ashx"
data = {
"address": user['address'],
"uid": uid,
"summary": summary,
"record": record,
"starttime": time.strftime("%Y-%m-%d"),
"dtype": 1,
"project": project
}
sign = calculate_sign(data, ADDITIONAL_TEXT)
header = generate_headers(sign, user['deviceId'], ADDITIONAL_TEXT, str(round(time.time() * 1000)))
info = send_request(url=url, method='POST', headers=header, data=data, proxy=proxy_data)
logging.info(info)
return json.loads(info)
def week_Report(time, user, uid, summary, record, project):
url = "http://sxbaapp.zcj.jyt.henan.gov.cn/api/ReportHandler.ashx"
data = {
"address": user['address'],
"uid": uid,
"summary": summary,
"record": record,
"starttime": (time + datetime.timedelta(days=-7)).strftime('%Y-%m-%d'),
"dtype": 2,
"project": project,
"endtime": time.strftime("%Y-%m-%d"),
"stype": 2
}
sign = calculate_sign(data, ADDITIONAL_TEXT)
header = generate_headers(sign, user['deviceId'], ADDITIONAL_TEXT, str(round(time.time() * 1000)))
info = send_request(url=url, method='POST', headers=header, data=data, proxy=proxy_data)
logging.info(info)
return info
def month_Report(time, user, uid, summary, record, project):
url = "http://sxbaapp.zcj.jyt.henan.gov.cn/api/ReportHandler.ashx"
data = {
"address": user['address'],
"uid": uid,
"summary": summary,
"record": record,
"starttime": (time + datetime.timedelta(days=-30)).strftime('%Y-%m-%d'),
"dtype": 2,
"project": project,
"endtime": time.strftime("%Y-%m-%d"),
"stype": 3
}
sign = calculate_sign(data, ADDITIONAL_TEXT)
header = generate_headers(sign, user['deviceId'], ADDITIONAL_TEXT, str(round(time.time() * 1000)))
info = send_request(url=url, method='POST', headers=header, data=data, proxy=proxy_data)
logging.info(info)
return info
def load_report_data_from_json(file_path):
if os.path.exists(file_path):
logging.info("检测到实习报告文件,已加载!")
else:
open(file_path, 'w', encoding='utf-8').write("[\n\n]")
logging.info(f"未检测到 {file_path} 文件,已自动创建!")
return json.load(open(file_path, 'r', encoding='utf-8'))
def report_handler(user):
if config.day_report:
day_report_data = load_users_from_json("day_report.json")
this_day_report_data = day_report_data[random.randint(0, (len(day_report_data) - 1))]
this_day_result = day_Report(datetime.datetime.now(), user,
json.loads(get_user_uid(user['deviceId'], user['phone'], user['password']))[
'data']['uid'],
this_day_report_data['summary'],
this_day_report_data['recored'],
this_day_report_data['project'])
try:
this_day_result_content = f"{this_day_result['msg']}"
except:
this_day_result_content = this_day_result
logging.info(this_day_result_content)
return this_day_result_content
if config.week_report:
if datetime.datetime.weekday(datetime.datetime.now()) == 6:
week_report_data = load_users_from_json("week_report.json")
this_week_report_data = week_report_data[random.randint(0, (len(week_report_data) - 1))]
this_week_result = day_Report(datetime.datetime.now(), user,
json.loads(get_user_uid(user['deviceId'], user['phone'], user['password']))[
'data']['uid'],
this_week_report_data['summary'],
this_week_report_data['recored'],
this_week_report_data['project'])
try:
this_week_result_content = f"{this_week_result['msg']}"
except:
this_week_result_content = this_week_result
logging.info(this_week_result_content)
return this_week_result_content
if config.month_report:
if datetime.datetime.now().strftime("%m") == "30":
month_report_data = load_report_data_from_json("month_report.json")
this_month_report_data = month_report_data[random.randint(0, (len(month_report_data) - 1))]
this_month_result = day_Report(datetime.datetime.now(), user,
json.loads(get_user_uid(user['deviceId'], user['phone'], user['password']))[
'data']['uid'],
this_month_report_data['summary'],
this_month_report_data['recored'],
this_month_report_data['project'])
try:
this_month_result_content = f"{this_month_result['msg']}"
except:
this_month_result_content = this_month_result
logging.info(this_month_result_content)
return this_month_result_content