ruff format

This commit is contained in:
mikumifa committed 2025-05-13 21:17:11 +08:00
1 parent 3061d88b87
commit d42f315c2d
21 files changed
+2113 -302

No files matched your search

+1
View File
@@ -0,0 +1 @@
3.11
+3 -1
View File
@@ -6,7 +6,9 @@ import sys
# 获取图标文件的路径
def get_application_path() -> str:
if getattr(sys, "frozen", False):
application_path = getattr(sys, '_MEIPASS', os.path.abspath(os.path.dirname(__file__)))
application_path = getattr(
sys, "_MEIPASS", os.path.abspath(os.path.dirname(__file__))
)
else:
application_path = os.path.dirname(os.path.abspath(__file__))
+65 -23
View File
@@ -21,6 +21,7 @@ from util.dynimport import bili_ticket_gt_python
# https://github.com/Amorter/biliTicker_gt/blob/f378891457bb78bcacf181eaf642b11f5543b4e0/src/click.rs#L166
def letterbox_resize(image, target_size=(384, 384), fill_color=(0, 0, 0)):
"""
使用左上角对齐方法调整图像大小。
@@ -40,8 +41,12 @@ def letterbox_resize(image, target_size=(384, 384), fill_color=(0, 0, 0)):
class Model:
def __init__(self, debugDir=None):
self.yolo = onnxruntime.InferenceSession(os.path.join(APP_PATH, "geetest", "model", "yolo.onnx"))
self.siamese = onnxruntime.InferenceSession(os.path.join(APP_PATH, "geetest", "model", "triple.onnx"))
self.yolo = onnxruntime.InferenceSession(
os.path.join(APP_PATH, "geetest", "model", "yolo.onnx")
)
self.siamese = onnxruntime.InferenceSession(
os.path.join(APP_PATH, "geetest", "model", "triple.onnx")
)
if debugDir:
os.makedirs(debugDir, exist_ok=True)
self.debugDir = debugDir
@@ -55,7 +60,9 @@ class Model:
input_shape = model_inputs[0].shape
input_width = input_shape[2]
input_height = input_shape[3]
self.origin_img = cv2.imdecode(np.frombuffer(img, np.uint8), cv2.IMREAD_ANYCOLOR)
self.origin_img = cv2.imdecode(
np.frombuffer(img, np.uint8), cv2.IMREAD_ANYCOLOR
)
img = Image.fromarray(self.origin_img)
img = letterbox_resize(img, (input_height, input_width))
image_data = np.array(img) / 255.0
@@ -85,7 +92,7 @@ class Model:
bg_imgs = []
bg_boxes = []
for i in ret_boxes:
cropped = self.origin_img[i[1]: i[1] + i[3], i[0]: i[0] + i[2]]
cropped = self.origin_img[i[1] : i[1] + i[3], i[0] : i[0] + i[2]]
if cropped.shape[0] < 35 and cropped.shape[1] < 35:
text_imgs.append(cropped.astype(np.float32))
text_boxes.append(i)
@@ -96,13 +103,21 @@ class Model:
def match(self, text_imgs, bg_imgs, bg_imgs_box):
text_imgs = np.stack(
[normalize_image(cv2.resize(img, self.size)).transpose(2, 0, 1) for img in text_imgs]) # (n, C, H, W)
[
normalize_image(cv2.resize(img, self.size)).transpose(2, 0, 1)
for img in text_imgs
]
) # (n, C, H, W)
bg_imgs = np.stack(
[normalize_image(cv2.resize(img, self.size)).transpose(2, 0, 1) for img in bg_imgs]) # (n, C, H, W)
[
normalize_image(cv2.resize(img, self.size)).transpose(2, 0, 1)
for img in bg_imgs
]
) # (n, C, H, W)
inputs = {'input': text_imgs}
inputs = {"input": text_imgs}
text_embeddings = self.siamese.run(None, inputs)[0]
inputs = {'input': bg_imgs}
inputs = {"input": bg_imgs}
bg_embeddings = self.siamese.run(None, inputs)[0]
similarity_matrix = 1 - cdist(text_embeddings, bg_embeddings, metric="cosine")
similarity_matrix = softmax(similarity_matrix, axis=1)
@@ -110,15 +125,30 @@ class Model:
std_sim = similarity_matrix.std(axis=1)
similarity_matrix = (similarity_matrix - mean_sim) / std_sim
row_ind, col_ind = linear_sum_assignment(-similarity_matrix)
result_list = sorted([(i, bg_imgs_box[j]) for i, j in zip(row_ind, col_ind)], key=lambda x: x[0])
result_list = sorted(
[(i, bg_imgs_box[j]) for i, j in zip(row_ind, col_ind)], key=lambda x: x[0]
)
match_scores = [similarity_matrix[i, j] for i, j in zip(row_ind, col_ind)]
if self.debugDir:
uid = uuid.uuid1()
for idx, i in result_list:
cv2.putText(self.origin_img, str(idx), (i[0] + 30, i[1] + 30), cv2.FONT_HERSHEY_SIMPLEX,
1, (255, 0, 0), 2, cv2.LINE_AA)
cv2.rectangle(self.origin_img, (i[0], i[1]), (i[0] + i[2], i[1] + i[3]), (0, 255, 0),
2) # Adjust size as needed
cv2.putText(
self.origin_img,
str(idx),
(i[0] + 30, i[1] + 30),
cv2.FONT_HERSHEY_SIMPLEX,
1,
(255, 0, 0),
2,
cv2.LINE_AA,
)
cv2.rectangle(
self.origin_img,
(i[0], i[1]),
(i[0] + i[2], i[1] + i[3]),
(0, 255, 0),
2,
) # Adjust size as needed
cv2.imwrite(os.path.join(self.debugDir, f"{uid}.jpg"), self.origin_img)
loguru.logger.debug(f"debug_image saved to {uid}.jpg")
return result_list, match_scores
@@ -132,11 +162,7 @@ def download_img(url: str) -> bytes:
def refresh(gt, challenge):
url = "http://api.geevisit.com/refresh.php"
params = {
"gt": gt,
"challenge": challenge,
"callback": "geetest_1717918222610"
}
params = {"gt": gt, "challenge": challenge, "callback": "geetest_1717918222610"}
res = requests.get(url, params=params)
res.raise_for_status()
@@ -181,10 +207,17 @@ class TripleValidator(Validator):
try:
before_calculate_key = time.time()
pic_content = download_img(args)
text_imgs, text_boxes, bg_imgs, bg_boxes = self.model.detect(pic_content)
if len(text_boxes) != len(bg_boxes) or len(text_boxes) == 1 or len(bg_boxes) == 1:
text_imgs, text_boxes, bg_imgs, bg_boxes = self.model.detect(
pic_content
)
if (
len(text_boxes) != len(bg_boxes)
or len(text_boxes) == 1
or len(bg_boxes) == 1
):
raise Exception(
f"detect error fast retry text_boxes: {len(text_boxes)} bg_boxes: {len(bg_boxes)}")
f"detect error fast retry text_boxes: {len(text_boxes)} bg_boxes: {len(bg_boxes)}"
)
result_list, output_res = self.model.match(text_imgs, bg_imgs, bg_boxes)
loguru.logger.debug(f"{output_res}")
point_list = []
@@ -192,7 +225,14 @@ class TripleValidator(Validator):
left = str(round((i[0] + 30) / 333 * 10000))
top = str(round((i[1] + 30) / 333 * 10000))
point_list.append(f"{left}_{top}")
w = self.click.generate_w(",".join(point_list), gt, challenge, str(list(c)), s, "abcdefghijklmnop")
w = self.click.generate_w(
",".join(point_list),
gt,
challenge,
str(list(c)),
s,
"abcdefghijklmnop",
)
w_use_time = time.time() - before_calculate_key
loguru.logger.debug(f"generation time: {w_use_time} seconds")
if w_use_time < 2:
@@ -209,5 +249,7 @@ class TripleValidator(Validator):
if __name__ == "__main__":
# 使用示例
validator = TripleValidator(debugDir=os.path.join(APP_PATH, "geetest", "debug", f"{time.time()}"))
validator = TripleValidator(
debugDir=os.path.join(APP_PATH, "geetest", "debug", f"{time.time()}")
)
test_validator(validator, n=100)
+2 -1
View File
@@ -23,7 +23,8 @@ def test_validator(validator, n=100, click=bili_ticket_gt_python.ClickPy()):
total_time = 0
for i in range(n):
gt, challenge = click.register_test(
"https://passport.bilibili.com/x/passport-login/captcha?source=main_web")
"https://passport.bilibili.com/x/passport-login/captcha?source=main_web"
)
start_time = time.time()
validate_string = validator.validate(gt, challenge)
elapsed_time = time.time() - start_time
+73 -39
View File
@@ -8,44 +8,48 @@ from task.buy import buy
from task.endpoint import start_heartbeat_thread
import os
def main():
parser = argparse.ArgumentParser(
description="Ticket Purchase Tool or Gradio UI")
def main():
parser = argparse.ArgumentParser(description="Ticket Purchase Tool or Gradio UI")
subparsers = parser.add_subparsers(dest="command")
# `--buy` 子命令
buy_parser = subparsers.add_parser(
"buy", help="Start the ticket buying function")
buy_parser.add_argument("tickets_info_str", type=str,
help="Ticket information in string format.")
buy_parser = subparsers.add_parser("buy", help="Start the ticket buying function")
buy_parser.add_argument(
"tickets_info_str", type=str, help="Ticket information in string format."
)
buy_parser.add_argument("interval", type=int, help="Interval time.")
buy_parser.add_argument("mode", type=int, help="Mode of operation.")
buy_parser.add_argument("total_attempts", type=int,
help="Total number of attempts.")
buy_parser.add_argument("timeoffset", type=float,
help="Time offset in seconds.")
buy_parser.add_argument(
"total_attempts", type=int, help="Total number of attempts."
)
buy_parser.add_argument("timeoffset", type=float, help="Time offset in seconds.")
buy_parser.add_argument("--endpoint_url", type=str, help="endpoint_url.")
buy_parser.add_argument("--time_start", type=str,
default="", help="Start time (optional")
buy_parser.add_argument("--audio_path", type=str,
default="", help="Path to audio file (optional).")
buy_parser.add_argument("--pushplusToken", type=str,
default="", help="PushPlus token (optional).")
buy_parser.add_argument("--serverchanKey", type=str,
default="", help="ServerChan key (optional).")
buy_parser.add_argument("--filename", type=str,
default="default", help="filename (optional).")
buy_parser.add_argument(
"--time_start", type=str, default="", help="Start time (optional"
)
buy_parser.add_argument(
"--audio_path", type=str, default="", help="Path to audio file (optional)."
)
buy_parser.add_argument(
"--pushplusToken", type=str, default="", help="PushPlus token (optional)."
)
buy_parser.add_argument(
"--serverchanKey", type=str, default="", help="ServerChan key (optional)."
)
buy_parser.add_argument(
"--filename", type=str, default="default", help="filename (optional)."
)
parser.add_argument("--port", type=int, default=7860, help="server port")
parser.add_argument("--share", type=bool, default=False,
help="create a public link")
parser.add_argument(
"--share", type=bool, default=False, help="create a public link"
)
args = parser.parse_args()
LOG_PATH = (os.environ.get("LOG_PATH", "logs/app.log"))
LOG_PATH = os.environ.get("LOG_PATH", "logs/app.log")
os.remove(LOG_PATH) if os.path.exists(LOG_PATH) else None
logger.remove()
logger.add(LOG_PATH, rotation="1 MB", retention="7 days", encoding="utf-8")
logger.add(lambda msg: print(msg, end=""), level="INFO")
@@ -53,15 +57,24 @@ def main():
if args.command == "buy":
logger.remove()
from const import BASE_DIR
os.makedirs(os.path.join(BASE_DIR, "log"), exist_ok=True)
log_file = os.path.join(BASE_DIR, "log", f"{uuid.uuid1()}.log")
logger.add(log_file, colorize=True,)
logger.add(
log_file,
colorize=True,
)
import gradio as gr
from pathlib import Path
Path(log_file).touch(exist_ok=True)
from gradio_log import Log
filename_only = os.path.basename(args.filename)
with gr.Blocks(title=f"{filename_only}", css="body {overflow-y: scroll;} .xterm-screen {min-height: 70vh; max-height: 70vh} footer {visibility: hidden}") as demo:
with gr.Blocks(
title=f"{filename_only}",
css="body {overflow-y: scroll;} .xterm-screen {min-height: 70vh; max-height: 70vh} footer {visibility: hidden}",
) as demo:
gr.Markdown(
f"""
# 当前抢票 {filename_only}
@@ -69,7 +82,11 @@ def main():
"""
)
Log(log_file, dark=True, xterm_scrollback=5000,)
Log(
log_file,
dark=True,
xterm_scrollback=5000,
)
def exit_program():
print(f"{filename_only} ,关闭程序...")
@@ -85,16 +102,26 @@ def main():
server_port=port,
share=False,
inbrowser=True,
prevent_thread_lock=True
prevent_thread_lock=True,
)
client = gradio_client.Client(args.endpoint_url)
assert demo.local_url
start_heartbeat_thread(
client, self_url=demo.local_url, to_url=args.endpoint_url, detail=filename_only)
client,
self_url=demo.local_url,
to_url=args.endpoint_url,
detail=filename_only,
)
buy(
args.tickets_info_str, args.time_start, args.interval, args.mode,
args.total_attempts, args.timeoffset, args.audio_path,
args.pushplusToken, args.serverchanKey
args.tickets_info_str,
args.time_start,
args.interval,
args.mode,
args.total_attempts,
args.timeoffset,
args.audio_path,
args.pushplusToken,
args.serverchanKey,
)
else:
@@ -112,10 +139,17 @@ def main():
"""
from const import BASE_DIR
log_file = os.path.join(BASE_DIR, "app.log")
logger.add(log_file, colorize=True,)
with gr.Blocks(title="biliTickerBuy", css="body {overflow-y: scroll;} .xterm-screen {min-height: 70vh; max-height: 70vh} footer {visibility: hidden}") as demo:
log_file = os.path.join(BASE_DIR, "app.log")
logger.add(
log_file,
colorize=True,
)
with gr.Blocks(
title="biliTickerBuy",
css="body {overflow-y: scroll;} .xterm-screen {min-height: 70vh; max-height: 70vh} footer {visibility: hidden}",
) as demo:
gr.Markdown(header)
with gr.Tab("生成配置"):
setting_tab()
@@ -130,12 +164,12 @@ def main():
# 运行应用
demo.launch(
share=args.share,
server_name="0.0.0.0", # 必须监听所有 IP
server_port=port # 使用 Cloud Run 提供的端口
server_port=port, # 使用 Cloud Run 提供的端口
)
if __name__ == "__main__":
main()
+30
View File
@@ -0,0 +1,30 @@
[project]
name = "bilitickerbuy"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.11"
dependencies = [
"bili-ticket-gt-python~=0.2.8",
"gradio~=4.44.1",
"gradio-calendar~=0.0.6",
"gradio-log~=0.0.4",
"install-playwright~=0.1.0",
"loguru~=0.7.2",
"ntplib~=0.4.0",
"numpy~=1.26.4",
"onnxruntime~=1.18.0",
"opencv-python~=4.11.0.86",
"pillow~=10.3.0",
"playsound3~=3.2.2",
"playwright~=1.46.0",
"pydantic~=2.8.2",
"qrcode~=7.4.2",
"requests~=2.31.0",
"retry~=0.9.2",
"scipy~=1.15.2",
"setuptools~=65.5.1",
"tinydb~=4.8.0",
]
[tool.mypy]
disable_error_code = ["import-untyped"]
+134 -64
View File
@@ -17,8 +17,9 @@ from util.error import withTimeString
ways = []
ways_detail = []
if bili_ticket_gt_python is not None:
ways_detail.insert(0, importlib.import_module(
"geetest.TripleValidator").TripleValidator())
ways_detail.insert(
0, importlib.import_module("geetest.TripleValidator").TripleValidator()
)
ways.insert(0, "本地过验证码v2(Amorter提供)")
# ways_detail.insert(0, importlib.import_module("geetest.AmorterValidator").AmorterValidator())
# ways.insert(0, "本地过验证码(Amorter提供)")
@@ -26,8 +27,14 @@ if bili_ticket_gt_python is not None:
def handle_error(message, e):
logger.error(message + str(e))
return [gr.update(value=withTimeString(f"有错误,具体查看控制台日志\n\n当前错误 {e}"), visible=True),
gr.update(visible=True), *[gr.update() for _ in range(6)]]
return [
gr.update(
value=withTimeString(f"有错误,具体查看控制台日志\n\n当前错误 {e}"),
visible=True,
),
gr.update(visible=True),
*[gr.update() for _ in range(6)],
]
def go_tab(demo: gr.Blocks):
@@ -47,18 +54,21 @@ def go_tab(demo: gr.Blocks):
""")
with gr.Row(equal_height=True):
upload_ui = gr.Files(
label="上传多个配置文件,点击不同的配置文件可快速切换", file_count="multiple")
ticket_ui = gr.TextArea(label="查看",
info="配置信息",
interactive=False)
label="上传多个配置文件,点击不同的配置文件可快速切换",
file_count="multiple",
)
ticket_ui = gr.TextArea(label="查看", info="配置信息", interactive=False)
gr.HTML("""<label for="datetime">程序已经提前帮你校准时间,设置成开票时间即可。请勿设置成开票前的时间。在开票前抢票会短暂封号</label><br>
<input type="datetime-local" id="datetime" name="datetime" step="1">""", label="选择抢票的时间",
show_label=True, )
gr.HTML(
"""<label for="datetime">程序已经提前帮你校准时间,设置成开票时间即可。请勿设置成开票前的时间。在开票前抢票会短暂封号</label><br>
<input type="datetime-local" id="datetime" name="datetime" step="1">""",
label="选择抢票的时间",
show_label=True,
)
def upload(filepath):
try:
with open(filepath[0], 'r', encoding="utf-8") as file:
with open(filepath[0], "r", encoding="utf-8") as file:
content = file.read()
return content
except Exception as e:
@@ -67,7 +77,7 @@ def go_tab(demo: gr.Blocks):
def file_select_handler(select_data: SelectData, files):
file_label = files[select_data.index]
try:
with open(file_label, 'r', encoding="utf-8") as file:
with open(file_label, "r", encoding="utf-8") as file:
content = file.read()
return content
except Exception as e:
@@ -77,45 +87,66 @@ def go_tab(demo: gr.Blocks):
upload_ui.select(file_select_handler, upload_ui, ticket_ui)
# 手动设置/更新时间偏差
with gr.Accordion(label='手动设置/更新时间偏差', open=False):
time_diff_ui = gr.Number(label="当前脚本时间偏差 (单位: ms)",
info="你可以在这里手动输入时间偏差, 或点击下面按钮自动更新当前时间偏差。正值将推迟相应时间开始抢票, 负值将提前相应时间开始抢票。",
value=format(time_service.get_timeoffset() * 1000, '.2f')) # type: ignore
with gr.Accordion(label="手动设置/更新时间偏差", open=False):
time_diff_ui = gr.Number(
label="当前脚本时间偏差 (单位: ms)",
info="你可以在这里手动输入时间偏差, 或点击下面按钮自动更新当前时间偏差。正值将推迟相应时间开始抢票, 负值将提前相应时间开始抢票。",
value=format(time_service.get_timeoffset() * 1000, ".2f"),
) # type: ignore
refresh_time_ui = gr.Button(value="点击自动更新时间偏差")
refresh_time_ui.click(fn=lambda: format(float(time_service.compute_timeoffset()) * 1000, '.2f'),
inputs=None, outputs=time_diff_ui)
time_diff_ui.change(fn=lambda x: time_service.set_timeoffset(format(float(x) / 1000, '.5f')),
inputs=time_diff_ui, outputs=None)
refresh_time_ui.click(
fn=lambda: format(
float(time_service.compute_timeoffset()) * 1000, ".2f"
),
inputs=None,
outputs=time_diff_ui,
)
time_diff_ui.change(
fn=lambda x: time_service.set_timeoffset(
format(float(x) / 1000, ".5f")
),
inputs=time_diff_ui,
outputs=None,
)
# 验证码选择
select_way = 0
way_select_ui = gr.Radio(ways, label="过验证码的方式", info="详细说明请前往 `训练你的验证码速度` 那一栏",
type="index", value=ways[select_way])
way_select_ui = gr.Radio(
ways,
label="过验证码的方式",
info="详细说明请前往 `训练你的验证码速度` 那一栏",
type="index",
value=ways[select_way],
)
with gr.Accordion(label='配置抢票声音提醒[可选]', open=False):
with gr.Accordion(label="配置抢票声音提醒[可选]", open=False):
with gr.Row():
audio_path_ui = gr.Audio(
label="上传提示声音[只支持格式wav]", type="filepath", loop=True)
with gr.Accordion(label='配置抢票消息提醒[可选]', open=False):
label="上传提示声音[只支持格式wav]", type="filepath", loop=True
)
with gr.Accordion(label="配置抢票消息提醒[可选]", open=False):
gr.Markdown(
"""
🗨️ 抢票成功提醒
> 你需要去对应的网站获取key或token,然后填入下面的输入框
> [Server酱](https://sct.ftqq.com/sendkey) | [pushplus](https://www.pushplus.plus/uc.html)
> 留空以不启用提醒功能
""")
"""
)
with gr.Row():
serverchan_ui = gr.Textbox(
value=configDB.get("serverchanKey") if configDB.get(
"serverchanKey") is not None else "",
value=configDB.get("serverchanKey")
if configDB.get("serverchanKey") is not None
else "",
label="Server酱的SendKey",
interactive=True,
info="https://sct.ftqq.com/",
)
pushplus_ui = gr.Textbox(
value=configDB.get("pushplusToken") if configDB.get(
"pushplusToken") is not None else "",
value=configDB.get("pushplusToken")
if configDB.get("pushplusToken") is not None
else "",
label="PushPlus的Token",
interactive=True,
info="https://www.pushplus.plus/",
@@ -127,8 +158,7 @@ def go_tab(demo: gr.Blocks):
def inner_input_pushplus(x):
return configDB.insert("pushplusToken", x)
serverchan_ui.change(
fn=inner_input_serverchan, inputs=serverchan_ui)
serverchan_ui.change(fn=inner_input_serverchan, inputs=serverchan_ui)
pushplus_ui.change(fn=inner_input_pushplus, inputs=pushplus_ui)
@@ -139,20 +169,36 @@ def go_tab(demo: gr.Blocks):
way_select_ui.change(choose_option, inputs=way_select_ui)
with gr.Row():
interval_ui = gr.Number(label="抢票间隔", value=300, minimum=1,
info="设置抢票任务之间的时间间隔(单位:毫秒),建议不要设置太小", )
mode_ui = gr.Radio(label="抢票次数", choices=["无限", "有限"], value="无限", info="选择抢票的次数",
type="index", interactive=True, )
total_attempts_ui = gr.Number(label="总过次数", value=100, minimum=1, info="设置抢票的总次数",
visible=False, )
interval_ui = gr.Number(
label="抢票间隔",
value=300,
minimum=1,
info="设置抢票任务之间的时间间隔(单位:毫秒),建议不要设置太小",
)
mode_ui = gr.Radio(
label="抢票次数",
choices=["无限", "有限"],
value="无限",
info="选择抢票的次数",
type="index",
interactive=True,
)
total_attempts_ui = gr.Number(
label="总过次数",
value=100,
minimum=1,
info="设置抢票的总次数",
visible=False,
)
def start_go(files, time_start, interval, mode, total_attempts, audio_path):
if not files:
return [gr.update(value=withTimeString("未提交抢票配置"), visible=True)]
yield [
gr.update(value=withTimeString("开始多开抢票,详细查看终端"), visible=True)]
gr.update(value=withTimeString("开始多开抢票,详细查看终端"), visible=True)
]
for filename in files:
with open(filename, 'r', encoding="utf-8") as file:
with open(filename, "r", encoding="utf-8") as file:
content = file.read()
filename_only = os.path.basename(filename)
logger.info(f"启动 {filename_only}")
@@ -160,38 +206,56 @@ def go_tab(demo: gr.Blocks):
proc = buy_new_terminal(
endpoint_url=demo.local_url,
filename=filename,
tickets_info_str=content, time_start=time_start, interval=interval, mode=mode,
total_attempts=total_attempts, audio_path=audio_path,
pushplusToken=configDB.get(
"pushplusToken"),
serverchanKey=configDB.get(
"serverchanKey"),
timeoffset=time_service.get_timeoffset())
tickets_info_str=content,
time_start=time_start,
interval=interval,
mode=mode,
total_attempts=total_attempts,
audio_path=audio_path,
pushplusToken=configDB.get("pushplusToken"),
serverchanKey=configDB.get("serverchanKey"),
timeoffset=time_service.get_timeoffset(),
)
return [gr.update()]
mode_ui.change(
fn=lambda x: gr.update(visible=True) if x == 1 else gr.update(visible=False), inputs=[mode_ui],
outputs=total_attempts_ui, )
fn=lambda x: gr.update(visible=True) if x == 1 else gr.update(visible=False),
inputs=[mode_ui],
outputs=total_attempts_ui,
)
with gr.Row():
go_btn = gr.Button("开始抢票")
with gr.Row():
go_ui = gr.Textbox(
info="此窗口为临时输出,具体请见控制台", label="输出信息", interactive=False, visible=False,
show_copy_button=True, max_lines=10,
info="此窗口为临时输出,具体请见控制台",
label="输出信息",
interactive=False,
visible=False,
show_copy_button=True,
max_lines=10,
)
_time_tmp = gr.Textbox(visible=False)
go_btn.click(fn=None, inputs=None, outputs=_time_tmp,
js='(x) => document.getElementById("datetime").value', )
Endpoint = namedtuple('Endpoint', ['endpoint', 'detail', 'update_at'])
go_btn.click(
fn=None,
inputs=None,
outputs=_time_tmp,
js='(x) => document.getElementById("datetime").value',
)
Endpoint = namedtuple("Endpoint", ["endpoint", "detail", "update_at"])
endpoint_details = {}
_report_tmp = gr.Button(visible=False)
_report_tmp.api_info
def available_endpoints() -> List[Endpoint]:
nonlocal endpoint_details
return [t for endpoint, t in endpoint_details.items() if time.time() - t.update_at < 3]
return [
t
for endpoint, t in endpoint_details.items()
if time.time() - t.update_at < 3
]
_end_point_tinput = gr.Textbox(visible=False)
@@ -199,9 +263,7 @@ def go_tab(demo: gr.Blocks):
nonlocal endpoint_details
now = time.time()
endpoint_details[end_point] = Endpoint(
endpoint=end_point,
detail=detail,
update_at=now
endpoint=end_point, detail=detail, update_at=now
)
_report_tmp.click(
@@ -212,6 +274,7 @@ def go_tab(demo: gr.Blocks):
def tick():
return f"当前时间戳:{int(time.time())}"
timer = gr.Textbox(label="定时更新", interactive=False, visible=False)
demo.load(fn=tick, inputs=None, outputs=timer, every=1)
@@ -225,12 +288,19 @@ def go_tab(demo: gr.Blocks):
for endpoint in endpoints:
with gr.Row():
text = gr.Button(
value=f"点击跳转 🚀 {endpoint.endpoint} {endpoint.detail}", link=endpoint.endpoint)
value=f"点击跳转 🚀 {endpoint.endpoint} {endpoint.detail}",
link=endpoint.endpoint,
)
go_btn.click(
fn=start_go,
inputs=[
upload_ui, _time_tmp, interval_ui, mode_ui, total_attempts_ui,
audio_path_ui],
outputs=[go_ui],)
upload_ui,
_time_tmp,
interval_ui,
mode_ui,
total_attempts_ui,
audio_path_ui,
],
outputs=[go_ui],
)
+5 -2
View File
@@ -1,7 +1,9 @@
import gradio as gr
import os
LOG_PATH = (os.environ.get("LOG_PATH", "logs/app.log"))
LOG_PATH = os.environ.get("LOG_PATH", "logs/app.log")
def read_last_logs(n=1000):
if not os.path.exists(LOG_PATH):
return "No logs found."
@@ -9,6 +11,7 @@ def read_last_logs(n=1000):
lines = f.readlines()
return "".join(lines[-n:])
def log_tab():
log_textbox = gr.Textbox(label="最近日志", lines=20, interactive=False)
refresh_btn = gr.Button("刷新日志")
@@ -16,4 +19,4 @@ def log_tab():
refresh_btn.click(fn=read_last_logs, inputs=None, outputs=log_textbox)
timer = gr.Timer(5.0)
timer.tick(fn=read_last_logs, outputs=log_textbox)
timer.tick(fn=read_last_logs, outputs=log_textbox)
+114 -77
View File
@@ -34,12 +34,12 @@ sales_flag_number_map = {
102: "已结束",
103: "未完成",
105: "下架",
106: "已取消"
106: "已取消",
}
def filename_filter(filename):
filename = re.sub('[/:*?"<>|]', '', filename)
filename = re.sub('[/:*?"<>|]', "", filename)
return filename
@@ -66,7 +66,8 @@ def on_submit_ticket_id(num):
gr.update(),
gr.update(),
gr.update(visible=False),
gr.update(value='输入无效,请输入一个有效的网址。', visible=True), gr.update()
gr.update(value="输入无效,请输入一个有效的网址。", visible=True),
gr.update(),
]
res = main_request.get(
url=f"https://show.bilibili.com/api/ticket/project/getV2?version=134&id={num}&project_id={num}"
@@ -75,24 +76,25 @@ def on_submit_ticket_id(num):
logger.debug(ret)
# 检查 errno
if ret.get('errno') == 100001:
if ret.get("errno") == 100001:
return [
gr.update(),
gr.update(),
gr.update(),
gr.update(),
gr.update(visible=True),
gr.update(value='输入无效,请输入一个有效的票ID。', visible=True), gr.update()
gr.update(value="输入无效,请输入一个有效的票ID。", visible=True),
gr.update(),
]
elif ret.get('errno') != 0:
elif ret.get("errno") != 0:
return [
gr.update(),
gr.update(),
gr.update(),
gr.update(),
gr.update(visible=True),
gr.update(value=ret.get('msg', '未知错误') +
'。', visible=True), gr.update()
gr.update(value=ret.get("msg", "未知错误") + "。", visible=True),
gr.update(),
]
data = ret["data"]
ticket_str_list = []
@@ -116,12 +118,14 @@ def on_submit_ticket_id(num):
item["project_id"] = data["id"]
# 场贩
good_list = main_request.get(
url=f'https://show.bilibili.com/api/ticket/linkgoods/list?project_id={project_id}&page_type=0')
url=f"https://show.bilibili.com/api/ticket/linkgoods/list?project_id={project_id}&page_type=0"
)
good_list = good_list.json()
ids = [item["id"] for item in good_list["data"]["list"]]
for id in ids:
good_detail = main_request.get(
url=f'https://show.bilibili.com/api/ticket/linkgoods/detail?link_id={id}')
url=f"https://show.bilibili.com/api/ticket/linkgoods/detail?link_id={id}"
)
good_detail = good_detail.json()
for item in good_detail["data"]["specs_list"]:
item["project_id"] = good_detail["data"]["item_id"]
@@ -151,7 +155,8 @@ def on_submit_ticket_id(num):
ticket_str = f"{screen_name} - {ticket_desc} - ¥{ticket_price / 100}- {ticket_can_buy} - 【起售时间:{sale_start}】"
ticket_str_list.append(ticket_str)
ticket_value.append(
{"project_id": screen["project_id"], "ticket": ticket})
{"project_id": screen["project_id"], "ticket": ticket}
)
buyer_json = main_request.get(
url=f"https://show.bilibili.com/api/ticket/buyer/list?is_default&projectId={project_id}"
@@ -178,9 +183,12 @@ def on_submit_ticket_id(num):
gr.update(visible=True),
gr.update(
value=f"{extracted_id_message}\n获取票信息成功:\n展会名称:{project_name}\n"
f"开展时间:{project_start_time} - {project_end_time}\n场馆地址:{venue_name} {venue_address}",
f"开展时间:{project_start_time} - {project_end_time}\n场馆地址:{venue_name} {venue_address}",
visible=True,
), gr.update(visible=True, value=sales_dates[0]) if sales_dates_show else gr.update(visible=False)
),
gr.update(visible=True, value=sales_dates[0])
if sales_dates_show
else gr.update(visible=False),
]
except Exception as e:
return [
@@ -189,37 +197,46 @@ def on_submit_ticket_id(num):
gr.update(),
gr.update(),
gr.update(),
gr.update(value=e, visible=True), gr.update()
gr.update(value=e, visible=True),
gr.update(),
]
def extract_id_from_url(url):
parsed_url = urlparse(url)
query_params = parse_qs(parsed_url.query)
return query_params.get('id', [None])[0]
return query_params.get("id", [None])[0]
def on_submit_all(ticket_id, ticket_info, people_indices, people_buyer_index, address_index):
def on_submit_all(
ticket_id, ticket_info, people_indices, people_buyer_index, address_index
):
try:
ticket_cur: list[dict[str, Any]] = ticket_value[ticket_info]
people_cur = [buyer_value[item] for item in people_indices]
people_buyer_cur = buyer_value[people_buyer_index]
ticket_id = extract_id_from_url(ticket_id)
if ticket_id is None:
return [gr.update(value="你所填不是网址,或者网址是错的", visible=True),
gr.update(value={}),
gr.update()]
return [
gr.update(value="你所填不是网址,或者网址是错的", visible=True),
gr.update(value={}),
gr.update(),
]
if len(people_indices) == 0:
return [gr.update(value="至少选一个实名人", visible=True),
gr.update(value={}),
gr.update()]
return [
gr.update(value="至少选一个实名人", visible=True),
gr.update(value={}),
gr.update(),
]
if addr_value is None:
return [gr.update(value="没有填写地址", visible=True),
gr.update(value={}),
gr.update()]
return [
gr.update(value="没有填写地址", visible=True),
gr.update(value={}),
gr.update(),
]
address_cur = addr_value[address_index]
username = main_request.get_request_name()
detail = f'{username}-{project_name}-{ticket_str_list[ticket_info]}'
detail = f"{username}-{project_name}-{ticket_str_list[ticket_info]}"
for p in people_cur:
detail += f"-{p['name']}"
config_dir = {
@@ -245,17 +262,26 @@ def on_submit_all(ticket_id, ticket_info, people_indices, people_buyer_index, ad
},
"cookies": main_request.cookieManager.get_cookies(),
"phone": main_request.cookieManager.get_config_value("phone", ""),
"https_proxy": main_request.cookieManager.get_config_value("https_proxy", ""),
"https_proxy": main_request.cookieManager.get_config_value(
"https_proxy", ""
),
}
if "link_id" in ticket_cur["ticket"]:
config_dir["link_id"] = ticket_cur["ticket"]["link_id"]
filename = os.path.join(TEMP_PATH, filename_filter(detail) + ".json")
with open(filename, 'w', encoding='utf-8') as f:
with open(filename, "w", encoding="utf-8") as f:
json.dump(config_dir, f, ensure_ascii=False, indent=4)
return [gr.update(), gr.update(value=config_dir, visible=True), gr.update(value=filename, visible=True)]
return [
gr.update(),
gr.update(value=config_dir, visible=True),
gr.update(value=filename, visible=True),
]
except Exception as e:
return [gr.update(value="生成错误,仔细看看你可能有哪里漏填的", visible=True), gr.update(value={}),
gr.update()]
return [
gr.update(value="生成错误,仔细看看你可能有哪里漏填的", visible=True),
gr.update(value={}),
gr.update(),
]
def setting_tab():
@@ -278,65 +304,69 @@ def setting_tab():
interactive=False,
info="输入配置文件使用的账号名称",
)
gr_file_ui = gr.File(
label="当前登录信息文件",
value=global_cookie_path)
gr_file_ui = gr.File(label="当前登录信息文件", value=global_cookie_path)
with gr.Row():
upload_ui = gr.UploadButton(label="导入")
add_btn = gr.Button("登录")
def upload_file(file):
try:
shutil.copy2(file.name, global_cookie_path)
set_main_request(BiliRequest(cookies_config_path=global_cookie_path))
name = main_request.get_request_name()
yield [
"导入成功",
gr.update(value=name),
gr.update(value=global_cookie_path)
"导入成功",
gr.update(value=name),
gr.update(value=global_cookie_path),
]
except Exception as e:
logger.exception(e)
name = main_request.get_request_name()
yield [
"登录出现错误",
gr.update(value=name),
gr.update(value=global_cookie_path)
"登录出现错误",
gr.update(value=name),
gr.update(value=global_cookie_path),
]
upload_ui.upload(
upload_file, [upload_ui], [
info_ui, username_ui, gr_file_ui])
upload_ui.upload(upload_file, [upload_ui], [info_ui, username_ui, gr_file_ui])
def add():
main_request.cookieManager.db.delete("cookie")
yield [
"已经注销,将打开浏览器,请在浏览器里面重新登录", gr.update(value="未登录"),
gr.update(value=global_cookie_path)]
"已经注销,将打开浏览器,请在浏览器里面重新登录",
gr.update(value="未登录"),
gr.update(value=global_cookie_path),
]
try:
main_request.cookieManager.get_cookies_str_force()
name = main_request.get_request_name()
yield [f"登录成功", gr.update(value=name), gr.update(value=global_cookie_path)]
yield [
f"登录成功",
gr.update(value=name),
gr.update(value=global_cookie_path),
]
except Exception:
name = main_request.get_request_name()
yield ["登录出现错误", gr.update(value=name), gr.update(value=global_cookie_path)]
yield [
"登录出现错误",
gr.update(value=name),
gr.update(value=global_cookie_path),
]
add_btn.click(
fn=add,
inputs=None,
outputs=[info_ui, username_ui, gr_file_ui]
)
with gr.Accordion(label='填写你的当前账号所绑定的手机号[可选]', open=False):
add_btn.click(fn=add, inputs=None, outputs=[info_ui, username_ui, gr_file_ui])
with gr.Accordion(label="填写你的当前账号所绑定的手机号[可选]", open=False):
phone_gate_ui = gr.Textbox(
label="填写你的当前账号所绑定的手机号", info="手机号验证出现概率极低,可不填",
value=main_request.cookieManager.get_config_value("phone", ""))
label="填写你的当前账号所绑定的手机号",
info="手机号验证出现概率极低,可不填",
value=main_request.cookieManager.get_config_value("phone", ""),
)
def input_phone(_phone):
main_request.cookieManager.set_config_value("phone", _phone)
phone_gate_ui.change(
fn=input_phone, inputs=phone_gate_ui, outputs=None)
phone_gate_ui.change(fn=input_phone, inputs=phone_gate_ui, outputs=None)
with gr.Accordion(label='填写你的HTTPS代理服务器[可选]', open=False):
with gr.Accordion(label="填写你的HTTPS代理服务器[可选]", open=False):
gr.Markdown("""
> **注意**:
@@ -348,15 +378,15 @@ def setting_tab():
""")
https_proxy_ui = gr.Textbox(
label="填写抢票时候的代理服务器地址", info="例如: http://127.0.0.1:8080",
value=main_request.cookieManager.get_config_value("https_proxy", ""))
label="填写抢票时候的代理服务器地址",
info="例如: http://127.0.0.1:8080",
value=main_request.cookieManager.get_config_value("https_proxy", ""),
)
def input_https_proxy(_https_proxy):
main_request.cookieManager.set_config_value(
"https_proxy", _https_proxy)
main_request.cookieManager.set_config_value("https_proxy", _https_proxy)
https_proxy_ui.change(
fn=input_https_proxy, inputs=https_proxy_ui, outputs=None)
https_proxy_ui.change(fn=input_https_proxy, inputs=https_proxy_ui, outputs=None)
with gr.Column():
ticket_id_ui = gr.Textbox(
@@ -374,8 +404,11 @@ def setting_tab():
info="必填,请仔细核对起售时间,千万别选错其他时间点的票",
)
date_ui = Calendar(
type="string", label="选择日期",
info="此票需要你选择的时间,时间是否有效请自行判断", interactive=True)
type="string",
label="选择日期",
info="此票需要你选择的时间,时间是否有效请自行判断",
interactive=True,
)
with gr.Row():
people_buyer_ui = gr.Dropdown(
label="联系人",
@@ -410,7 +443,7 @@ def setting_tab():
people_buyer_ui,
address_ui,
],
outputs=[info_ui, config_output_ui, config_file_ui]
outputs=[info_ui, config_output_ui, config_file_ui],
)
ticket_id_btn.click(
@@ -423,7 +456,7 @@ def setting_tab():
address_ui,
inner,
info_ui,
date_ui
date_ui,
],
)
@@ -433,8 +466,8 @@ def setting_tab():
try:
ticket_that_day = main_request.get(
url=f'https://show.bilibili.com/api/ticket/project/infoByDate?id={project_id}&date={_date}').json()[
"data"]
url=f"https://show.bilibili.com/api/ticket/project/infoByDate?id={project_id}&date={_date}"
).json()["data"]
ticket_str_list = []
ticket_value = []
for screen in ticket_that_day["screen_list"]:
@@ -444,25 +477,29 @@ def setting_tab():
for ticket in screen["ticket_list"]:
ticket_desc = ticket["desc"]
sale_start = ticket["sale_start"]
ticket["price"] = ticket_price = ticket["price"] + \
express_fee
ticket["price"] = ticket_price = ticket["price"] + express_fee
ticket["screen"] = screen_name
ticket["screen_id"] = screen_id
ticket_can_buy = "可购买" if ticket["clickable"] else "不可购买"
ticket_str = (
f"{screen_name} - {ticket_desc} - ¥{ticket_price / 100}- {ticket_can_buy}"
f" - 【起售时间:{sale_start}】")
f" - 【起售时间:{sale_start}】"
)
ticket_str_list.append(ticket_str)
ticket_value.append(
{"project_id": project_id, "ticket": ticket})
{"project_id": project_id, "ticket": ticket}
)
return [gr.update(value=_date, visible=True), gr.update(choices=ticket_str_list),
gr.update(value=f"当前票日期更新为: {_date}")]
return [
gr.update(value=_date, visible=True),
gr.update(choices=ticket_str_list),
gr.update(value=f"当前票日期更新为: {_date}"),
]
except Exception as e:
return [gr.update(), gr.update(), gr.update(value=e, visible=True)]
date_ui.change(
fn=on_submit_date,
inputs=date_ui,
outputs=[date_ui, ticket_info_ui, info_ui]
outputs=[date_ui, ticket_info_ui, info_ui],
)
+18 -9
View File
@@ -19,9 +19,13 @@ def train_tab():
_request = main_request
# 验证码选择
way_select_ui = gr.Radio(
ways, label="验证码", info="过验证码的方式", type="index", value=ways[0])
api_key_input_ui = gr.Textbox(label="api_key", value=_request.cookieManager.get_config_value("appkey", ""),
visible=False)
ways, label="验证码", info="过验证码的方式", type="index", value=ways[0]
)
api_key_input_ui = gr.Textbox(
label="api_key",
value=_request.cookieManager.get_config_value("appkey", ""),
visible=False,
)
select_way = 0
def choose_option(way):
@@ -35,8 +39,7 @@ def train_tab():
else:
return gr.update(visible=False)
way_select_ui.change(choose_option, inputs=way_select_ui,
outputs=api_key_input_ui)
way_select_ui.change(choose_option, inputs=way_select_ui, outputs=api_key_input_ui)
test_get_challenge_btn = gr.Button("开始测试")
test_log = gr.JSON(label="测试结果(显示验证码过期则说明成功)")
@@ -92,7 +95,7 @@ def train_tab():
gr.update(visible=True), # test_gt_row
gr.update(value="重新生成"), # test_get_challenge_btn
gr.update(value={}),
gr.update(value=uuid.uuid1())
gr.update(value=uuid.uuid1()),
]
def run_validation():
@@ -129,14 +132,20 @@ def train_tab():
gr.update(visible=False), # test_gt_row
gr.update(value="重新生成"), # test_get_challenge_btn
gr.update(value=test_data.json()),
gr.update()
gr.update(),
]
test_get_challenge_btn.click(
fn=test_get_challenge,
inputs=[api_key_input_ui],
outputs=[test_gt_ui, test_challenge_ui, test_gt_row,
test_get_challenge_btn, test_log, trigger_ui],
outputs=[
test_gt_ui,
test_challenge_ui,
test_gt_row,
test_get_challenge_btn,
test_log,
trigger_ui,
],
)
trigger_ui.change(
fn=None,
+99 -46
View File
@@ -22,13 +22,21 @@ from util.error import ERRNO_DICT
from util.order_qrcode import get_qrcode_url
if bili_ticket_gt_python is not None:
Amort = importlib.import_module(
"geetest.TripleValidator").TripleValidator()
Amort = importlib.import_module("geetest.TripleValidator").TripleValidator()
@logger.catch
def buy(tickets_info_str, time_start, interval, mode, total_attempts, timeoffset, audio_path, pushplusToken,
serverchanKey):
def buy(
tickets_info_str,
time_start,
interval,
mode,
total_attempts,
timeoffset,
audio_path,
pushplusToken,
serverchanKey,
):
if bili_ticket_gt_python is None:
logger.info("当前设备不支持本地过验证码,无法使用")
return
@@ -38,28 +46,40 @@ def buy(tickets_info_str, time_start, interval, mode, total_attempts, timeoffset
cookies = tickets_info["cookies"]
https_proxy = tickets_info.get("https_proxy", None)
phone = tickets_info.get("phone", None)
tickets_info.pop('cookies', None)
tickets_info['buyer_info'] = json.dumps(tickets_info['buyer_info'])
tickets_info['deliver_info'] = json.dumps(tickets_info['deliver_info'])
tickets_info.pop("cookies", None)
tickets_info["buyer_info"] = json.dumps(tickets_info["buyer_info"])
tickets_info["deliver_info"] = json.dumps(tickets_info["deliver_info"])
if https_proxy:
logger.info(f"使用代理: {https_proxy}")
_request = BiliRequest(cookies=cookies, proxy={'https': https_proxy})
_request = BiliRequest(cookies=cookies, proxy={"https": https_proxy})
else:
_request = BiliRequest(cookies=cookies)
token_payload = {"count": tickets_info["count"], "screen_id": tickets_info["screen_id"], "order_type": 1,
"project_id": tickets_info["project_id"], "sku_id": tickets_info["sku_id"], "token": "",
"newRisk": True, }
token_payload = {
"count": tickets_info["count"],
"screen_id": tickets_info["screen_id"],
"order_type": 1,
"project_id": tickets_info["project_id"],
"sku_id": tickets_info["sku_id"],
"token": "",
"newRisk": True,
}
if time_start != "":
logger.info("0) 等待开始时间")
logger.info("时间偏差已被设置为: " + str(timeoffset) + 's')
logger.info("时间偏差已被设置为: " + str(timeoffset) + "s")
try:
time_difference = (
datetime.strptime(time_start, "%Y-%m-%dT%H:%M:%S").timestamp() - time.time() + timeoffset)
datetime.strptime(time_start, "%Y-%m-%dT%H:%M:%S").timestamp()
- time.time()
+ timeoffset
)
except ValueError as e:
time_difference = (
datetime.strptime(time_start, "%Y-%m-%dT%H:%M").timestamp() - time.time() + timeoffset)
datetime.strptime(time_start, "%Y-%m-%dT%H:%M").timestamp()
- time.time()
+ timeoffset
)
start_time = time.perf_counter()
end_time = start_time + time_difference
current_time = start_time
@@ -71,17 +91,19 @@ def buy(tickets_info_str, time_start, interval, mode, total_attempts, timeoffset
logger.info(f"1)订单准备")
request_result_normal = _request.post(
url=f"https://show.bilibili.com/api/ticket/order/prepare?project_id={tickets_info['project_id']}",
data=token_payload, isJson=True)
data=token_payload,
isJson=True,
)
request_result = request_result_normal.json()
logger.info(
f"请求头: {request_result_normal.headers} // 请求体: {request_result}")
code = int(request_result.get("errno", request_result.get('code')))
f"请求头: {request_result_normal.headers} // 请求体: {request_result}"
)
code = int(request_result.get("errno", request_result.get("code")))
# 完成验证码
if code == -401:
# if True:
_url = "https://api.bilibili.com/x/gaia-vgate/v1/register"
_payload = urlencode(
request_result["data"]["ga_data"]["riskParams"])
_payload = urlencode(request_result["data"]["ga_data"]["riskParams"])
_data = _request.post(_url, _payload).json()
logger.info(f"验证码请求: {_data}")
csrf = _request.cookieManager.get_cookies_value("bili_jct")
@@ -89,30 +111,41 @@ def buy(tickets_info_str, time_start, interval, mode, total_attempts, timeoffset
if _data["data"]["type"] == "geetest":
gt = _data["data"]["geetest"]["gt"]
challenge = _data["data"]["geetest"]["challenge"]
geetest_validate = Amort.validate(
gt=gt, challenge=challenge)
geetest_validate = Amort.validate(gt=gt, challenge=challenge)
geetest_seccode = geetest_validate + "|jordan"
logger.info(
f"geetest_validate: {geetest_validate},geetest_seccode: {geetest_seccode}")
f"geetest_validate: {geetest_validate},geetest_seccode: {geetest_seccode}"
)
_url = "https://api.bilibili.com/x/gaia-vgate/v1/validate"
_payload = {"challenge": challenge, "token": token, "seccode": geetest_seccode, "csrf": csrf,
"validate": geetest_validate, }
_payload = {
"challenge": challenge,
"token": token,
"seccode": geetest_seccode,
"csrf": csrf,
"validate": geetest_validate,
}
_data = _request.post(_url, urlencode(_payload)).json()
elif _data["data"]["type"] == "phone":
_payload = {"code": phone, "csrf": csrf, "token": token, }
_payload = {
"code": phone,
"csrf": csrf,
"token": token,
}
_data = _request.post(_url, urlencode(_payload)).json()
else:
logger.warning("这个一个程序无法应对的验证码,脚本无法处理")
break
logger.info(f"validate: {_data}")
if int(_data.get("errno", _data.get('code'))) == 0:
if int(_data.get("errno", _data.get("code"))) == 0:
logger.info("验证码成功")
else:
logger.info("验证码失败 {}", _data)
continue
request_result = _request.post(
url=f"https://show.bilibili.com/api/ticket/order/prepare?project_id={tickets_info['project_id']}",
data=token_payload, isJson=True).json()
data=token_payload,
isJson=True,
).json()
logger.info(f"prepare: {request_result}")
tickets_info["again"] = 1
tickets_info["token"] = request_result["data"]["token"]
@@ -127,12 +160,15 @@ def buy(tickets_info_str, time_start, interval, mode, total_attempts, timeoffset
raise ValueError("抢票结束")
ret = _request.post(
url=f"https://show.bilibili.com/api/ticket/order/createV2?project_id={tickets_info['project_id']}",
data=payload, isJson=True).json()
err = int(ret.get("errno", ret.get('code')))
data=payload,
isJson=True,
).json()
err = int(ret.get("errno", ret.get("code")))
logger.info(
f'状态码: {err}({ERRNO_DICT.get(err, "未知错误码")}), 响应: {ret}')
f"状态码: {err}({ERRNO_DICT.get(err, '未知错误码')}), 响应: {ret}"
)
if err == 100034:
logger.info(f'更新票价为:{ret["data"]["pay_money"] / 100}')
logger.info(f"更新票价为:{ret['data']['pay_money'] / 100}")
tickets_info["pay_money"] = ret["data"]["pay_money"]
payload = tickets_info
if err == 0 or err == 100048 or err == 100079:
@@ -146,11 +182,14 @@ def buy(tickets_info_str, time_start, interval, mode, total_attempts, timeoffset
request_result, errno = inner_request()
left_time_str = "无限" if mode == 0 else left_time
logger.info(
f'状态码: {errno}({ERRNO_DICT.get(errno, "未知错误码")}), 响应: {request_result} 剩余次数: {left_time_str}')
f"状态码: {errno}({ERRNO_DICT.get(errno, '未知错误码')}), 响应: {request_result} 剩余次数: {left_time_str}"
)
if errno == 0:
logger.info(f"3)抢票成功,弹出付款二维码")
qrcode_url = get_qrcode_url(
_request, request_result["data"]["orderId"], )
_request,
request_result["data"]["orderId"],
)
qr_gen = qrcode.QRCode()
qr_gen.add_data(qrcode_url)
qr_gen.make(fit=True)
@@ -158,10 +197,12 @@ def buy(tickets_info_str, time_start, interval, mode, total_attempts, timeoffset
qr_gen_image.show() # type: ignore
if pushplusToken:
PushPlusUtil.send_message(
pushplusToken, "抢票成功", "前往订单中心付款吧")
pushplusToken, "抢票成功", "前往订单中心付款吧"
)
if serverchanKey:
ServerChanUtil.send_message(
serverchanKey, "抢票成功", "前往订单中心付款吧")
serverchanKey, "抢票成功", "前往订单中心付款吧"
)
if audio_path:
playsound(audio_path)
break
@@ -182,17 +223,31 @@ def buy(tickets_info_str, time_start, interval, mode, total_attempts, timeoffset
def buy_new_terminal(
endpoint_url, filename,
tickets_info_str, time_start, interval, mode, total_attempts, audio_path, pushplusToken,
serverchanKey, timeoffset) -> subprocess.Popen:
endpoint_url,
filename,
tickets_info_str,
time_start,
interval,
mode,
total_attempts,
audio_path,
pushplusToken,
serverchanKey,
timeoffset,
) -> subprocess.Popen:
command = [sys.executable]
if not getattr(sys, "frozen", False):
command.extend(["main.py"])
command.extend([
"buy",
tickets_info_str, str(interval), str(mode), str(total_attempts),
str(timeoffset),
])
command.extend(
[
"buy",
tickets_info_str,
str(interval),
str(mode),
str(total_attempts),
str(timeoffset),
]
)
if time_start:
command.extend(["--time_start", time_start])
if audio_path:
@@ -203,7 +258,5 @@ def buy_new_terminal(
command.extend(["--serverchanKey", serverchanKey])
command.extend(["--filename", filename])
command.extend(["--endpoint_url", endpoint_url])
proc = subprocess.Popen(
command
)
proc = subprocess.Popen(command)
return proc
+6 -4
View File
@@ -5,16 +5,18 @@ from gradio_client import Client
from loguru import logger
def start_heartbeat_thread(client: Client, self_url: str, to_url: str, detail: str = ""):
def start_heartbeat_thread(
client: Client, self_url: str, to_url: str, detail: str = ""
):
def report_heart(client: Client, self_url: str, to_url: str, detail: str = ""):
cnt = 0
try:
res = client.predict(
self_url, detail,
self_url,
detail,
api_name="/report",
)
logger.debug(
f"report_heart {self_url} -({res})-> {to_url}")
logger.debug(f"report_heart {self_url} -({res})-> {to_url}")
cnt = 0
except Exception as e:
cnt += 1
+9 -8
View File
@@ -8,18 +8,20 @@ from util.CookieManager import CookieManager
class BiliRequest:
def __init__(self, headers=None, cookies=None, cookies_config_path=None, proxy=None):
def __init__(
self, headers=None, cookies=None, cookies_config_path=None, proxy=None
):
self.session = requests.Session()
self.session.proxies = proxy or {}
self.cookieManager = CookieManager(cookies_config_path, cookies)
self.headers = headers or {
'accept': '*/*',
'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6,zh-TW;q=0.5,ja;q=0.4',
'content-type': 'application/x-www-form-urlencoded',
"accept": "*/*",
"accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6,zh-TW;q=0.5,ja;q=0.4",
"content-type": "application/x-www-form-urlencoded",
"cookie": "",
"referer": "https://show.bilibili.com/",
'priority': 'u=1, i',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0',
"priority": "u=1, i",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0",
}
def get(self, url, data=None, isJson=False):
@@ -55,8 +57,7 @@ class BiliRequest:
if not self.cookieManager.have_cookies():
loguru.logger.warning("获取用户名失败,请重新登录")
return "未登录"
result = self.get(
"https://api.bilibili.com/x/web-interface/nav").json()
result = self.get("https://api.bilibili.com/x/web-interface/nav").json()
return result["data"]["uname"]
except Exception as e:
loguru.logger.exception(e)
+1 -2
View File
@@ -12,9 +12,8 @@ class CookieManager:
@logger.catch
def _login_and_save_cookies(
self, login_url="https://show.bilibili.com/platform/home.html"
self, login_url="https://show.bilibili.com/platform/home.html"
):
logger.info("启动浏览器中,第一次启动会比较慢,请使用在浏览器登录")
with sync_playwright() as p:
try:
+4 -4
View File
@@ -13,17 +13,17 @@ class KVDatabase:
def insert(self, key, value):
# 如果键已经存在,更新其值;否则插入新键值对
if self.db.contains(self.KeyValue.key == key):
self.db.update({'value': value}, self.KeyValue.key == key)
self.db.update({"value": value}, self.KeyValue.key == key)
else:
self.db.insert({'key': key, 'value': value})
self.db.insert({"key": key, "value": value})
def get(self, key):
result = self.db.get(self.KeyValue.key == key)
return result['value'] if result else None
return result["value"] if result else None
def update(self, key, value):
if self.db.contains(self.KeyValue.key == key):
self.db.update({'value': value}, self.KeyValue.key == key)
self.db.update({"value": value}, self.KeyValue.key == key)
else:
raise KeyError(f"Key '{key}' not found in database.")
+2 -11
View File
@@ -4,21 +4,12 @@ import loguru
import requests
def send_message(token, content, title):
try:
url = "http://www.pushplus.plus/send"
headers = {
"Content-Type": "application/json"
}
headers = {"Content-Type": "application/json"}
data = {
"token": token,
"content": content,
"title": title
}
data = {"token": token, "content": content, "title": title}
requests.post(url, headers=headers, data=json.dumps(data))
except Exception as e:
loguru.logger.info("PushPlus消息发送失败")
+2 -7
View File
@@ -8,14 +8,9 @@ import requests
def send_message(token, desp, title):
try:
url = f"https://sctapi.ftqq.com/{token}.send"
headers = {
"Content-Type": "application/json"
}
headers = {"Content-Type": "application/json"}
data = {
"desp": desp,
"title": title
}
data = {"desp": desp, "title": title}
requests.post(url, headers=headers, data=json.dumps(data))
except Exception as e:
loguru.logger.info("ServerChan消息发送失败")
+5 -2
View File
@@ -1,12 +1,15 @@
from base64 import urlsafe_b64encode
def generate_token(project_id: int, screen_id: int, order_type: int, count: int, sku_id: int) -> str:
def generate_token(
project_id: int, screen_id: int, order_type: int, count: int, sku_id: int
) -> str:
"""
生成Token
# reference: https://github.com/biliticket/transition-ticket/blob/d32fcf4399bd04b96e382ae791514867ad97612c/util/Bilibili/__init__.py#L230
Base64: URLSafeBase64
"""
def encrypt(char: int, encrypt_type: str) -> str:
"""
加密
@@ -54,4 +57,4 @@ def generate_token(project_id: int, screen_id: int, order_type: int, count: int,
token = "w" + p1 + "A" + p2 + "A" + p3 + p4 + "A" + p5 + p6 + "."
return token
return token
+3 -1
View File
@@ -7,7 +7,9 @@ from util.BiliRequest import BiliRequest
from util.KVDatabase import KVDatabase
from util.TimeService import TimeService
loguru.logger.debug(f"设置路径, APP_PATH={APP_PATH} TEMP_PATH={TEMP_PATH} BASE_DIR={BASE_DIR}")
loguru.logger.debug(
f"设置路径, APP_PATH={APP_PATH} TEMP_PATH={TEMP_PATH} BASE_DIR={BASE_DIR}"
)
configDB = KVDatabase(os.path.join(BASE_DIR, "config.json"))
global_cookie_path = os.path.join(BASE_DIR, "cookies.json")
main_request = BiliRequest(cookies_config_path=global_cookie_path)
+1 -1
View File
@@ -13,7 +13,7 @@ ERRNO_DICT = {
100048: "已经下单,有尚未完成订单",
100017: "票种不可售",
100051: "订单准备过期,重新验证",
100034: "票价错误"
100034: "票价错误",
}
Generated
+1536
View File
File diff suppressed because it is too large. Load diff