Merge pull request #229 from yongjer/master

Refactor code to follow pep8, f-string and others
master
Max 2024-04-24 15:21:19 +08:00 committed by GitHub
commit 1411dbc01a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 80 additions and 103 deletions

View File

@ -1,49 +1,44 @@
import base64 import base64
import json
from io import BytesIO
import requests import requests
from io import BytesIO
from PIL import Image from PIL import Image
from typing import Optional
from requests.exceptions import RequestException
class NonBrowser:
def __init__(self, domain_name: str = "tixcraft.com") -> None:
self.session = requests.Session()
self.set_domain(domain_name)
class NonBrowser(): def set_cookies(self, cookies: Optional[dict]) -> bool:
def __init__(self, domain_name = "tixcraft.com") -> None: if cookies is not None:
self.Session = requests.session() [self.session.cookies.set(cookie["name"], cookie["value"]) for cookie in cookies]
self.Set_Domain(domain_name) return True
return False
def Set_cookies(self, cookies:dict): def get_cookies(self) -> dict:
ret = False return self.session.cookies.get_dict()
if not cookies is None:
for cookie in cookies:
self.Session.cookies.set(cookie["name"],cookie["value"])
ret = True
return ret
def Get_cookies(self): def set_headers(self, header: str) -> None:
return self.Session.cookies.get_dict() self.session.headers = header
def set_headers(self, header:str): def set_domain(self, domain_name: str, captcha_url: str = "ticket/captcha", refresh_url: str = "ticket/captcha?refresh=1") -> None:
self.Session.headers = header self.url = f"https://{domain_name}/{captcha_url}"
self.refresh_url = f"https://{domain_name}/{refresh_url}"
def Set_Domain(self, domain_name, captcha_url="ticket/captcha", refresh_url="ticket/captcha?refresh=1"): def request_captcha(self) -> bytes:
self.url = "https://%s/%s" % (domain_name, captcha_url) response = self.session.get(self.url, stream=True)
self.refresh_url = "https://%s/%s" % (domain_name, refresh_url) img = Image.open(BytesIO(response.content))
def Request_Captcha(self):
img = Image.open(BytesIO(self.Session.get(self.url, stream = True).content))
output_buffer = BytesIO() output_buffer = BytesIO()
img.save(output_buffer, format='JPEG') img.save(output_buffer, format='JPEG')
binary_data = output_buffer.getvalue() binary_data = output_buffer.getvalue()
base64_data = base64.b64encode(binary_data) return base64.b64encode(binary_data)
return base64_data
def Request_Refresh_Captcha(self) -> str: def request_refresh_captcha(self) -> str:
try: try:
result = self.Session.get(self.refresh_url, stream = True) response = self.session.get(self.refresh_url, stream=True)
if result.status_code == 200: if response.status_code == 200:
json_data = json.loads(result.text) return response.json().get("url", "")
return json_data.get("url","") except RequestException:
else: pass
return ""
except Exception as e:
return "" return ""

View File

@ -69,7 +69,7 @@ https://max-everyday.com/2023/11/buy-ticket-by-vm/
### Step 3: 安裝第三方套件: ### Step 3: 安裝第三方套件:
<code>python3 -m pip install -r pip-req.txt</code> <code>python3 -m pip install -r requirement.txt</code>
### Step 4: 執行設定介面主桯式: ### Step 4: 執行設定介面主桯式:

View File

@ -2039,7 +2039,7 @@ def tixcraft_get_ocr_answer(driver, ocr, ocr_captcha_image_source, Captcha_Brows
if ocr_captcha_image_source == CONST_OCR_CAPTCH_IMAGE_SOURCE_NON_BROWSER: if ocr_captcha_image_source == CONST_OCR_CAPTCH_IMAGE_SOURCE_NON_BROWSER:
if not Captcha_Browser is None: if not Captcha_Browser is None:
img_base64 = base64.b64decode(Captcha_Browser.Request_Captcha()) img_base64 = base64.b64decode(Captcha_Browser.request_captcha())
if ocr_captcha_image_source == CONST_OCR_CAPTCH_IMAGE_SOURCE_CANVAS: if ocr_captcha_image_source == CONST_OCR_CAPTCH_IMAGE_SOURCE_CANVAS:
image_id = 'TicketForm_verifyCode-image' image_id = 'TicketForm_verifyCode-image'
@ -2073,7 +2073,7 @@ def tixcraft_get_ocr_answer(driver, ocr, ocr_captcha_image_source, Captcha_Brows
if img_base64 is None: if img_base64 is None:
if not Captcha_Browser is None: if not Captcha_Browser is None:
print("canvas get image fail, use plan_b: NonBrowser") print("canvas get image fail, use plan_b: NonBrowser")
img_base64 = base64.b64decode(Captcha_Browser.Request_Captcha()) img_base64 = base64.b64decode(Captcha_Browser.request_captcha())
except Exception as exc: except Exception as exc:
if show_debug_message: if show_debug_message:
print("canvas exception:", str(exc)) print("canvas exception:", str(exc))
@ -2152,7 +2152,7 @@ def tixcraft_auto_ocr(driver, ocr, away_from_keyboard_enable, previous_answer, C
else: else:
# Non_Browser solution. # Non_Browser solution.
if not Captcha_Browser is None: if not Captcha_Browser is None:
new_captcha_url = Captcha_Browser.Request_Refresh_Captcha() #取得新的CAPTCHA new_captcha_url = Captcha_Browser.request_refresh_captcha() #取得新的CAPTCHA
if new_captcha_url != "": if new_captcha_url != "":
tixcraft_change_captcha(driver, new_captcha_url) #更改CAPTCHA圖 tixcraft_change_captcha(driver, new_captcha_url) #更改CAPTCHA圖
else: else:
@ -5730,10 +5730,10 @@ def set_non_browser_cookies(driver, url, Captcha_Browser):
#PS: need set cookies once, if user change domain. #PS: need set cookies once, if user change domain.
if not Captcha_Browser is None: if not Captcha_Browser is None:
try: try:
Captcha_Browser.Set_cookies(driver.get_cookies()) Captcha_Browser.set_cookies(driver.get_cookies())
except Exception as e: except Exception as e:
pass pass
Captcha_Browser.Set_Domain(domain_name) Captcha_Browser.set_domain(domain_name)
def ticketmaster_parse_zone_info(driver, config_dict): def ticketmaster_parse_zone_info(driver, config_dict):
show_debug_message = True # debug. show_debug_message = True # debug.
@ -7007,7 +7007,7 @@ def ibon_auto_ocr(driver, config_dict, ocr, away_from_keyboard_enable, previous_
img_base64 = None img_base64 = None
if ocr_captcha_image_source == CONST_OCR_CAPTCH_IMAGE_SOURCE_NON_BROWSER: if ocr_captcha_image_source == CONST_OCR_CAPTCH_IMAGE_SOURCE_NON_BROWSER:
if not Captcha_Browser is None: if not Captcha_Browser is None:
img_base64 = base64.b64decode(Captcha_Browser.Request_Captcha()) img_base64 = base64.b64decode(Captcha_Browser.request_captcha())
if ocr_captcha_image_source == CONST_OCR_CAPTCH_IMAGE_SOURCE_CANVAS: if ocr_captcha_image_source == CONST_OCR_CAPTCH_IMAGE_SOURCE_CANVAS:
image_id = 'chk_pic' image_id = 'chk_pic'
image_element = None image_element = None
@ -7072,7 +7072,7 @@ def ibon_auto_ocr(driver, config_dict, ocr, away_from_keyboard_enable, previous_
else: else:
# Non_Browser solution. # Non_Browser solution.
if not Captcha_Browser is None: if not Captcha_Browser is None:
new_captcha_url = Captcha_Browser.Request_Refresh_Captcha() #取得新的CAPTCHA new_captcha_url = Captcha_Browser.request_refresh_captcha() #取得新的CAPTCHA
if new_captcha_url != "": if new_captcha_url != "":
#PS:[TODO] #PS:[TODO]
#tixcraft_change_captcha(driver, new_captcha_url) #更改CAPTCHA圖 #tixcraft_change_captcha(driver, new_captcha_url) #更改CAPTCHA圖
@ -7245,7 +7245,7 @@ def ibon_main(driver, url, config_dict, ocr, Captcha_Browser):
captcha_url = '/pic.aspx?TYPE=%s' % (model_name) captcha_url = '/pic.aspx?TYPE=%s' % (model_name)
#PS: need set cookies once, if user change domain. #PS: need set cookies once, if user change domain.
if not Captcha_Browser is None: if not Captcha_Browser is None:
Captcha_Browser.Set_Domain(domain_name, captcha_url=captcha_url) Captcha_Browser.set_domain(domain_name, captcha_url=captcha_url)
is_captcha_sent = ibon_captcha(driver, config_dict, ocr, Captcha_Browser, model_name) is_captcha_sent = ibon_captcha(driver, config_dict, ocr, Captcha_Browser, model_name)
@ -8984,7 +8984,7 @@ def kham_auto_ocr(driver, config_dict, ocr, away_from_keyboard_enable, previous_
img_base64 = None img_base64 = None
if ocr_captcha_image_source == CONST_OCR_CAPTCH_IMAGE_SOURCE_NON_BROWSER: if ocr_captcha_image_source == CONST_OCR_CAPTCH_IMAGE_SOURCE_NON_BROWSER:
if not Captcha_Browser is None: if not Captcha_Browser is None:
img_base64 = base64.b64decode(Captcha_Browser.Request_Captcha()) img_base64 = base64.b64decode(Captcha_Browser.request_captcha())
if ocr_captcha_image_source == CONST_OCR_CAPTCH_IMAGE_SOURCE_CANVAS: if ocr_captcha_image_source == CONST_OCR_CAPTCH_IMAGE_SOURCE_CANVAS:
image_id = 'chk_pic' image_id = 'chk_pic'
image_element = None image_element = None
@ -9049,7 +9049,7 @@ def kham_auto_ocr(driver, config_dict, ocr, away_from_keyboard_enable, previous_
else: else:
# Non_Browser solution. # Non_Browser solution.
if not Captcha_Browser is None: if not Captcha_Browser is None:
new_captcha_url = Captcha_Browser.Request_Refresh_Captcha() #取得新的CAPTCHA new_captcha_url = Captcha_Browser.request_refresh_captcha() #取得新的CAPTCHA
if new_captcha_url != "": if new_captcha_url != "":
#PS:[TODO] #PS:[TODO]
#tixcraft_change_captcha(driver, new_captcha_url) #更改CAPTCHA圖 #tixcraft_change_captcha(driver, new_captcha_url) #更改CAPTCHA圖
@ -9169,8 +9169,8 @@ def kham_main(driver, url, config_dict, ocr, Captcha_Browser):
if config_dict["ocr_captcha"]["enable"]: if config_dict["ocr_captcha"]["enable"]:
if not Captcha_Browser is None: if not Captcha_Browser is None:
Captcha_Browser.Set_cookies(driver.get_cookies()) Captcha_Browser.set_cookies(driver.get_cookies())
Captcha_Browser.Set_Domain(domain_name) Captcha_Browser.set_domain(domain_name)
break break
#https://kham.com.tw/application/UTK02/UTK0201_.aspx?PRODUCT_ID=XXX #https://kham.com.tw/application/UTK02/UTK0201_.aspx?PRODUCT_ID=XXX
@ -9264,7 +9264,7 @@ def kham_main(driver, url, config_dict, ocr, Captcha_Browser):
captcha_url = '/pic.aspx?TYPE=%s' % (model_name) captcha_url = '/pic.aspx?TYPE=%s' % (model_name)
#PS: need set cookies once, if user change domain. #PS: need set cookies once, if user change domain.
if not Captcha_Browser is None: if not Captcha_Browser is None:
Captcha_Browser.Set_Domain(domain_name, captcha_url=captcha_url) Captcha_Browser.set_domain(domain_name, captcha_url=captcha_url)
is_captcha_sent = False is_captcha_sent = False
@ -9332,7 +9332,7 @@ def kham_main(driver, url, config_dict, ocr, Captcha_Browser):
captcha_url = '/pic.aspx?TYPE=%s' % (model_name) captcha_url = '/pic.aspx?TYPE=%s' % (model_name)
#PS: need set cookies once, if user change domain. #PS: need set cookies once, if user change domain.
if not Captcha_Browser is None: if not Captcha_Browser is None:
Captcha_Browser.Set_Domain(domain_name, captcha_url=captcha_url) Captcha_Browser.set_domain(domain_name, captcha_url=captcha_url)
is_captcha_sent = False is_captcha_sent = False
if config_dict["ocr_captcha"]["enable"]: if config_dict["ocr_captcha"]["enable"]:
@ -9382,7 +9382,7 @@ def kham_main(driver, url, config_dict, ocr, Captcha_Browser):
captcha_url = '/pic.aspx?TYPE=%s' % (model_name) captcha_url = '/pic.aspx?TYPE=%s' % (model_name)
#PS: need set cookies once, if user change domain. #PS: need set cookies once, if user change domain.
if not Captcha_Browser is None: if not Captcha_Browser is None:
Captcha_Browser.Set_Domain(domain_name, captcha_url=captcha_url) Captcha_Browser.set_domain(domain_name, captcha_url=captcha_url)
kham_captcha(driver, config_dict, ocr, Captcha_Browser, model_name) kham_captcha(driver, config_dict, ocr, Captcha_Browser, model_name)
@ -10197,7 +10197,7 @@ def ticketplus_auto_ocr(driver, config_dict, ocr, previous_answer, Captcha_Brows
img_base64 = None img_base64 = None
if ocr_captcha_image_source == CONST_OCR_CAPTCH_IMAGE_SOURCE_NON_BROWSER: if ocr_captcha_image_source == CONST_OCR_CAPTCH_IMAGE_SOURCE_NON_BROWSER:
if not Captcha_Browser is None: if not Captcha_Browser is None:
img_base64 = base64.b64decode(Captcha_Browser.Request_Captcha()) img_base64 = base64.b64decode(Captcha_Browser.request_captcha())
if ocr_captcha_image_source == CONST_OCR_CAPTCH_IMAGE_SOURCE_CANVAS: if ocr_captcha_image_source == CONST_OCR_CAPTCH_IMAGE_SOURCE_CANVAS:
image_id = 'span.captcha-img' image_id = 'span.captcha-img'
image_element = None image_element = None
@ -10660,8 +10660,8 @@ def ticketplus_main(driver, url, config_dict, ocr, Captcha_Browser):
if config_dict["ocr_captcha"]["enable"]: if config_dict["ocr_captcha"]["enable"]:
domain_name = url.split('/')[2] domain_name = url.split('/')[2]
if not Captcha_Browser is None: if not Captcha_Browser is None:
Captcha_Browser.Set_cookies(driver.get_cookies()) Captcha_Browser.set_cookies(driver.get_cookies())
Captcha_Browser.Set_Domain(domain_name) Captcha_Browser.set_domain(domain_name)
is_user_signin = ticketplus_account_auto_fill(driver, config_dict) is_user_signin = ticketplus_account_auto_fill(driver, config_dict)
if is_user_signin: if is_user_signin:

View File

@ -111,8 +111,7 @@ def get_config_dict(args):
config_filepath = os.path.join(app_root, CONST_MAXBOT_CONFIG_FILE) config_filepath = os.path.join(app_root, CONST_MAXBOT_CONFIG_FILE)
# allow assign config by command line. # allow assign config by command line.
if not args.input is None: if args.input and len(args.input) > 0:
if len(args.input) > 0:
config_filepath = args.input config_filepath = args.input
config_dict = None config_dict = None
@ -121,48 +120,33 @@ def get_config_dict(args):
with open(config_filepath) as json_data: with open(config_filepath) as json_data:
config_dict = json.load(json_data) config_dict = json.load(json_data)
if not args.headless is None: # Define a dictionary to map argument names to their paths in the config_dict
config_dict["advanced"]["headless"] = util.t_or_f(args.headless) arg_to_path = {
"headless": ["advanced", "headless"],
"homepage": ["homepage"],
"ticket_number": ["ticket_number"],
"browser": ["browser"],
"tixcraft_sid": ["advanced", "tixcraft_sid"],
"ibonqware": ["advanced", "ibonqware"],
"kktix_account": ["advanced", "kktix_account"],
"kktix_password": ["advanced", "kktix_password_plaintext"],
"proxy_server": ["advanced", "proxy_server_port"],
"window_size": ["advanced", "window_size"]
}
if not args.homepage is None: # Update the config_dict based on the arguments
if len(args.homepage) > 0: for arg, path in arg_to_path.items():
config_dict["homepage"] = args.homepage value = getattr(args, arg)
if value and len(str(value)) > 0:
if not args.ticket_number is None: d = config_dict
if args.ticket_number > 0: for key in path[:-1]:
config_dict["ticket_number"] = args.ticket_number d = d[key]
d[path[-1]] = value
if not args.browser is None:
if len(args.browser) > 0:
config_dict["browser"] = args.browser
if not args.tixcraft_sid is None:
if len(args.tixcraft_sid) > 0:
config_dict["advanced"]["tixcraft_sid"] = args.tixcraft_sid
if not args.ibonqware is None:
if len(args.ibonqware) > 0:
config_dict["advanced"]["ibonqware"] = args.ibonqware
if not args.kktix_account is None:
if len(args.kktix_account) > 0:
config_dict["advanced"]["kktix_account"] = args.kktix_account
if not args.kktix_password is None:
if len(args.kktix_password) > 0:
config_dict["advanced"]["kktix_password_plaintext"] = args.kktix_password
if not args.proxy_server is None:
if len(args.proxy_server) > 2:
config_dict["advanced"]["proxy_server_port"] = args.proxy_server
if not args.window_size is None:
if len(args.window_size) > 2:
config_dict["advanced"]["window_size"] = args.window_size
# special case for headless to enable away from keyboard mode. # special case for headless to enable away from keyboard mode.
is_headless_enable_ocr = False is_headless_enable_ocr = False
if config_dict["advanced"]["headless"]: if config_dict["advanced"]["headless"]:
# for tixcraft headless. # for tixcraft headless.
#print("If you are runnig headless mode on tixcraft, you need input your cookie SID.")
if len(config_dict["advanced"]["tixcraft_sid"]) > 1: if len(config_dict["advanced"]["tixcraft_sid"]) > 1:
is_headless_enable_ocr = True is_headless_enable_ocr = True
@ -207,20 +191,18 @@ async def nodriver_press_button(tab, select_query):
print(e) print(e)
pass pass
async def nodriver_check_checkbox(tab, select_query, value='true'): from typing import Optional
is_checkbox_checked = False
async def nodriver_check_checkbox(tab: Optional[object], select_query: str, value: str = 'true') -> bool:
if tab: if tab:
try: try:
element = await tab.query_selector(select_query) element = await tab.query_selector(select_query)
if element: if element:
#await element.apply('function (element) { element.checked='+ value +'; } ')
await element.click() await element.click()
is_checkbox_checked = True return True
except Exception as exc: except Exception as exc:
#print("check checkbox fail for selector:", select_query)
print(exc) print(exc)
pass return False
return is_checkbox_checked
async def nodriver_facebook_login(tab, facebook_account, facebook_password): async def nodriver_facebook_login(tab, facebook_account, facebook_password):
if tab: if tab:
@ -1376,8 +1358,8 @@ async def nodriver_ticketplus_main(tab, url, config_dict, ocr, Captcha_Browser):
domain_name = url.split('/')[2] domain_name = url.split('/')[2]
if not Captcha_Browser is None: if not Captcha_Browser is None:
# TODO: # TODO:
#Captcha_Browser.Set_cookies(driver.get_cookies()) #Captcha_Browser.set_cookies(driver.get_cookies())
Captcha_Browser.Set_Domain(domain_name) Captcha_Browser.set_domain(domain_name)
is_user_signin = await nodriver_ticketplus_account_auto_fill(tab, config_dict) is_user_signin = await nodriver_ticketplus_account_auto_fill(tab, config_dict)
@ -1603,7 +1585,7 @@ async def nodriver_ibon_main(tab, url, config_dict, ocr, Captcha_Browser):
captcha_url = '/pic.aspx?TYPE=%s' % (model_name) captcha_url = '/pic.aspx?TYPE=%s' % (model_name)
#PS: need set cookies once, if user change domain. #PS: need set cookies once, if user change domain.
if not Captcha_Browser is None: if not Captcha_Browser is None:
Captcha_Browser.Set_Domain(domain_name, captcha_url=captcha_url) Captcha_Browser.set_domain(domain_name, captcha_url=captcha_url)
# TODO: # TODO:
#is_captcha_sent = ibon_captcha(driver, config_dict, ocr, Captcha_Browser, model_name) #is_captcha_sent = ibon_captcha(driver, config_dict, ocr, Captcha_Browser, model_name)