-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
463 lines (385 loc) · 14.5 KB
/
app.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
"""
@Author: ImYrS Yang
@Date: 2023/2/10
@Copyright: ImYrS Yang
@Description:
"""
import logging
from os import environ
from typing import NoReturn, Optional
import json
import argparse
import time
from configobj import ConfigObj
import requests
from modules import cqhttp, dingtalk, feishu, pushdeer, pushplus, serverchan, smtp, telegram, webhook
import github
class SignIn:
"""
签到
"""
def __init__(
self,
config: ConfigObj | dict,
refresh_token: str,
do_not_reward: Optional[bool] = False,
):
"""
初始化
:param config: 配置文件, ConfigObj 对象或字典
:param refresh_token: refresh_token
:param do_not_reward: 是否不领取奖励
"""
self.config = config
self.refresh_token = refresh_token
self.hide_refresh_token = self.__hide_refresh_token()
self.access_token = None
self.new_refresh_token = None
self.phone = None
self.signin_count = 0
self.signin_reward = None
self.error = None
self.do_not_reward = do_not_reward
def __hide_refresh_token(self) -> str:
"""
隐藏 refresh_token
:return: 隐藏后的 refresh_token
"""
try:
return self.refresh_token[:4] + '*' * len(self.refresh_token[4:-4]) + self.refresh_token[-4:]
except IndexError:
return self.refresh_token
def __get_access_token(self, retry: bool = False) -> bool:
"""
获取 access_token
:param retry: 是否重试
:return: 是否成功
"""
try:
data = requests.post(
'https://auth.aliyundrive.com/v2/account/token',
json={
'grant_type': 'refresh_token',
'refresh_token': self.refresh_token,
}
).json()
except requests.RequestException as e:
logging.error(f'[{self.hide_refresh_token}] 获取 access token 请求失败: {e}')
if not retry:
logging.info(f'[{self.hide_refresh_token}] 正在重试...')
return self.__get_access_token(retry=True)
self.error = e
return False
try:
if data['code'] in [
'RefreshTokenExpired', 'InvalidParameter.RefreshToken',
]:
logging.error(f'[{self.hide_refresh_token}] 获取 access token 失败, 可能是 refresh token 无效.')
self.error = data
return False
except KeyError:
pass
try:
self.access_token = data['access_token']
self.new_refresh_token = data['refresh_token']
self.phone = data['user_name']
except KeyError:
logging.error(f'[{self.hide_refresh_token}] 获取 access token 失败, 参数缺失: {data}')
self.error = f'获取 access token 失败, 参数缺失: {data}'
return False
return True
def __sign_in(self, retry: bool = False) -> NoReturn:
"""
签到函数
:return:
"""
try:
data = requests.post(
'https://member.aliyundrive.com/v1/activity/sign_in_list',
params={'_rx-s': 'mobile'},
headers={'Authorization': f'Bearer {self.access_token}'},
json={'isReward': False},
).json()
logging.debug(str(data))
except requests.RequestException as e:
logging.error(f'[{self.phone}] 签到请求失败: {e}')
if not retry:
logging.info(f'[{self.phone}] 正在重试...')
return self.__sign_in(retry=True)
self.error = e
return
if data['code'] == 'AccessTokenInvalid':
logging.error(f'[{self.phone}] access token 无效, 正在重新获取...')
if not retry:
logging.info(f'[{self.phone}] 签到失败, 正在重试...')
return self.__sign_in(retry=True)
if 'success' not in data:
logging.error(f'[{self.phone}] 签到失败, 错误信息: {data}')
self.error = data
return
self.signin_count = data['result']['signInCount']
if self.do_not_reward:
if self.signin_count < len(data['result']['signInLogs']):
logging.info(f'[{self.phone}] 已设置不领取奖励.')
self.signin_reward = '跳过领取奖励'
return
self.__reward_all(len(data['result']['signInLogs']))
return
try:
data = requests.post(
'https://member.aliyundrive.com/v1/activity/sign_in_reward',
params={'_rx-s': 'mobile'},
headers={'Authorization': f'Bearer {self.access_token}'},
json={'signInDay': self.signin_count},
).json()
logging.debug(str(data))
except requests.RequestException as e:
logging.error(f'[{self.phone}] 兑换请求失败: {e}')
if not retry:
logging.info(f'[{self.phone}] 正在重试...')
return self.__sign_in(retry=True)
reward = (
'无奖励'
if not data['result']
else f'获得 {data["result"]["name"]} {data["result"]["description"]}'
)
self.signin_reward = reward
logging.info(f'[{self.phone}] 签到成功, 本月累计签到 {self.signin_count} 天.')
logging.info(f'[{self.phone}] 本次签到{reward}')
def __reward_all(self, max_day: int) -> NoReturn:
"""
兑换当月全部奖励
:param max_day: 最大天数
:return:
"""
url = 'https://member.aliyundrive.com/v1/activity/sign_in_reward'
params = {'_rx-s': 'mobile'}
headers = {'Authorization': f'Bearer {self.access_token}'}
for day in range(1, max_day + 1):
try:
requests.post(
url,
params=params,
headers=headers,
json={'signInDay': day},
)
except requests.RequestException as e:
logging.error(f'[{self.phone}] 签到请求失败: {e}')
self.signin_reward = '已自动领取本月全部奖励'
def __generate_result(self) -> dict:
"""
获取签到结果
:return: 签到结果
"""
user = self.phone or self.hide_refresh_token
text = (
f'[{user}] 签到成功, 本月累计签到 {self.signin_count} 天.\n本次签到{self.signin_reward}'
if not self.error
else f'[{user}] 签到失败\n{json.dumps(str(self.error), indent=2, ensure_ascii=False)}'
)
text_html = (
f'<code>{user}</code> 签到成功, 本月累计签到 {self.signin_count} 天.\n本次签到{self.signin_reward}'
if not self.error
else (
f'<code>{user}</code> 签到失败\n'
f'<code>{json.dumps(str(self.error), indent=2, ensure_ascii=False)}</code>'
)
)
return {
'success': True if self.signin_count else False,
'user': self.phone or self.hide_refresh_token,
'refresh_token': self.new_refresh_token or self.refresh_token,
'count': self.signin_count,
'reward': self.signin_reward,
'text': text,
'text_html': text_html,
}
def run(self) -> dict:
"""
运行签到
:return: 签到结果
"""
result = self.__get_access_token()
if result:
time.sleep(3)
self.__sign_in()
return self.__generate_result()
def push(
config: ConfigObj | dict,
content: str,
content_html: str,
title: Optional[str] = None,
) -> NoReturn:
"""
推送签到结果
:param config: 配置文件, ConfigObj 对象或字典
:param content: 推送内容
:param content_html: 推送内容, HTML 格式
:param title: 推送标题
:return:
"""
configured_push_types = [
i.lower().strip()
for i in (
[config['push_types']]
if type(config['push_types']) == str
else config['push_types']
)
]
for push_type, pusher in {
'go-cqhttp': cqhttp,
'dingtalk': dingtalk,
'feishu': feishu,
'pushdeer': pushdeer,
'pushplus': pushplus,
'serverchan': serverchan,
'smtp': smtp,
'telegram': telegram,
'webhook': webhook,
}.items():
if push_type in configured_push_types:
pusher.push(config, content, content_html, title)
def init_logger(debug: Optional[bool] = False) -> NoReturn:
"""
初始化日志系统
:return:
"""
log = logging.getLogger()
log.setLevel(logging.DEBUG)
log_format = logging.Formatter(
'%(asctime)s - %(filename)s:%(lineno)d - %(levelname)s: %(message)s'
)
# Console
ch = logging.StreamHandler()
log.setLevel(logging.DEBUG if debug else logging.INFO)
ch.setFormatter(log_format)
log.addHandler(ch)
# Log file
log_name = 'aliyun_auto_signin.log'
fh = logging.FileHandler(log_name, mode='a', encoding='utf-8')
log.setLevel(logging.DEBUG if debug else logging.INFO)
fh.setFormatter(log_format)
log.addHandler(fh)
def get_config_from_env() -> Optional[dict]:
"""
从环境变量获取配置
:return: 配置字典, 配置缺失返回 None
"""
try:
refresh_tokens = environ['REFRESH_TOKENS'] or ''
push_types = environ['PUSH_TYPES'] or ''
return {
'refresh_tokens': refresh_tokens.split(','),
'push_types': push_types.split(','),
'serverchan_send_key': environ['SERVERCHAN_SEND_KEY'],
'telegram_endpoint': 'https://api.telegram.org',
'telegram_bot_token': environ['TELEGRAM_BOT_TOKEN'],
'telegram_chat_id': environ['TELEGRAM_CHAT_ID'],
'telegram_proxy': None,
'pushplus_token': environ['PUSHPLUS_TOKEN'],
'pushplus_topic': environ['PUSHPLUS_TOPIC'],
'smtp_host': environ['SMTP_HOST'],
'smtp_port': environ['SMTP_PORT'],
'smtp_tls': environ['SMTP_TLS'],
'smtp_user': environ['SMTP_USER'],
'smtp_password': environ['SMTP_PASSWORD'],
'smtp_sender': environ['SMTP_SENDER'],
'smtp_receiver': environ['SMTP_RECEIVER'],
'feishu_webhook': environ['FEISHU_WEBHOOK'],
'webhook_url': environ['WEBHOOK_URL'],
'cqhttp_endpoint': environ['CQHTTP_ENDPOINT'],
'cqhttp_user_id': environ['CQHTTP_USER_ID'],
'cqhttp_access_token': environ['CQHTTP_ACCESS_TOKEN'],
}
except KeyError as e:
logging.error(f'环境变量 {e} 缺失.')
return None
def get_args() -> argparse.Namespace:
"""
获取命令行参数
:return: 命令行参数
"""
parser = argparse.ArgumentParser(description='阿里云盘自动签到 by @ImYrS')
parser.add_argument('-a', '--action', help='由 GitHub Actions 调用', action='store_true', default=False)
parser.add_argument('-d', '--debug', help='调试模式, 会输出更多调试数据', action='store_true', default=False)
parser.add_argument('--do-not-reward', help='仅签到, 不进行奖励兑换', action='store_true', default=False)
return parser.parse_args()
def main():
"""
主函数
:return:
"""
environ['NO_PROXY'] = '*' # 禁止代理
args = get_args()
init_logger(args.debug) # 初始化日志系统
# 获取配置
config = (
get_config_from_env()
if args.action
else ConfigObj('config.ini', encoding='UTF8')
)
if not config:
logging.error('获取配置失败.')
raise ValueError('获取配置失败.')
# 获取所有 refresh token 指向用户
users = (
[config['refresh_tokens']]
if type(config['refresh_tokens']) == str
else config['refresh_tokens']
)
results = []
do_not_reward = (
environ['DO_NOT_REWARD'] == 'true'
if args.action
else
args.do_not_reward
)
for user in users:
signin = SignIn(
config=config,
refresh_token=user,
do_not_reward=do_not_reward,
)
results.append(signin.run())
# 合并推送
text = '\n\n'.join([i['text'] for i in results])
text_html = '\n\n'.join([i['text_html'] for i in results])
if args.action and not environ['GP_TOKEN']:
text += (
'\n\n当前 Actions 尚未配置 GP_TOKEN, 请参考 '
'https://imyrs.cn/posts/2023/auto-signin-aliyundrive-by-using-github-action/#github-personal-token'
' 尽快处理.'
)
text_html += (
'\n\n当前 Actions 尚未配置 GP_TOKEN, 请参考 '
'https://imyrs.cn/posts/2023/auto-signin-aliyundrive-by-using-github-action/#github-personal-token'
' 尽快处理.'
)
new_platform = (
'\n\n[通知] 新一代签到平台发布!\n\n'
'经过一个月的测试, 现在向你推荐由原班人马开发的新阿里云盘签到平台!\n\n'
'官网: https://aliyundrive.pro\n\n'
'- 免费, 快速, 可视化, 高可用性\n'
'- 支持最新版签到任务, 可自动完成上传文件, 观看视频等任务\n'
'- 每天推送太吵了? 支持仅签到失败时才推送\n'
'- 可同时绑定多个账号, 分别配置签到参数, 可视化配置更轻松\n'
'- 每天定时签到怕风控? 可以配置每天随机事件签到!\n'
'- 每周自动参加战队 PK, 帮你领取补签卡\n'
'- 害怕隐私风险? 可在登陆页面查看完整的隐私条款, 个人隐私是底线!\n\n'
'更多问题请在 GitHub issue 中提出, 或加入交流群 https://t.me/aliyun_auto_signin'
)
text += new_platform
text_html += new_platform
push(config, text, text_html, '阿里云盘签到')
# 更新 refresh token
new_users = [i['refresh_token'] for i in results]
if not args.action:
config['refresh_tokens'] = ','.join(new_users)
else:
try:
github.update_secret('REFRESH_TOKENS', ','.join(new_users))
logging.info('refresh tokens 更新成功.')
except Exception as e:
logging.error(f'更新 refresh tokens 失败: {e}')
if __name__ == '__main__':
main()