Skip to content

Commit

Permalink
feat: optimize login steps
Browse files Browse the repository at this point in the history
- 优化 登录逻辑
- 优化 Token 刷新逻辑
- 移除 LoginHelper SSL 模式覆盖
  • Loading branch information
txperl committed Oct 31, 2024
1 parent b41463d commit 6b6ea8d
Show file tree
Hide file tree
Showing 6 changed files with 109 additions and 118 deletions.
7 changes: 3 additions & 4 deletions app/config/language/en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ app.core.biu:
success_to_login: "Login successful"
config:
hint_port_is_in_use: "Current port is in use, please modify the 'sys.host' item in config.yml"
hint_proxy_in_use: "Proxy enabled"
hint_proxy_in_use: "Proxy %s enabled"
fail_to_load_config: "Failed to load configuration file, program cannot run normally"
outdated:
hint_latest: "Latest"
Expand All @@ -16,7 +16,7 @@ app.core.biu:
network:
hint_in_check: "Checking network status..."
fail_pixiv_and_use_bypass: "Cannot access Pixiv, enabling bypassSNI route (may not work properly)"
loginHelper:
login:
hint_token_only: "Due to Pixiv blocking username/password login, only token login is available now"
hint_before_start: "Network detection will begin shortly, this process can reduce the probability of being unable to use PixivBiu normally due to network issues"
fail_to_get_token_due_to_network: "Your network cannot properly perform Pixiv token login, please adjust and try again"
Expand All @@ -37,9 +37,8 @@ app.core.biu:

app.common.loginHelper:
network:
hint_in_check: "Checking network status..."
press_need_to_type_proxy: "Please enter proxy address (can be empty): "
hint_detect_proxy_and_continue: "Detected proxy address as %s, continue? (y / n): "
hint_detect_proxy: "Detected proxy address as %s, need to change? (y / n): "
is_need_to_type_proxy: "No proxy address detected, need to set manually? (y / n): "
login:
hint_intro_step_head: "[Login] Please follow these steps:"
Expand Down
7 changes: 3 additions & 4 deletions app/config/language/es.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ app.core.biu:
success_to_login: "inicio de sesión exitoso
config:
hint_port_is_in_use: "El puerto esta ocupado, please change the sys-host setting item in config.yml"
hint_proxy_in_use: "Proxy esta habilitado"
hint_proxy_in_use: "Proxy %s habilitado"
fail_to_load_config: "Fallo para cargar el archivo de configuracion, PixivBiu no puede correr correctamente"
outdated:
hint_latest: "Reciente"
Expand All @@ -16,7 +16,7 @@ app.core.biu:
network:
hint_in_check: "Comprobando estado de la red..."
fail_pixiv_and_use_bypass: "No se puede conectar a Pixiv, habilitar la ruta bypassSNI (puede no estar disponible temporalmente)"
loginHelper:
login:
hint_token_only: "Dado que Pixiv deshabilita el inicio de sesión con contraseña, por ahora solo puedes usar token para iniciar sesión"
hint_before_start: "La detección de red está a punto de comenzar, este proceso puede reducir la probabilidad de no poder usar PixivBiu debido a problemas de red"
fail_to_get_token_due_to_network: "Su red no está funcionando correctamente para iniciar sesión con el token Pixiv; ajústela y vuelva a intentarlo."
Expand All @@ -37,9 +37,8 @@ app.core.biu:

app.common.loginHelper:
network:
hint_in_check: "Comprobando estado de la red..."
press_need_to_type_proxy: "Por favor, introduzca la dirección del proxy (puede estar en blanco): "
hint_detect_proxy_and_continue: "Dirección de proxy (%s) detectada, ¿desea cambiarla? (y / n): "
hint_detect_proxy: "Dirección de proxy detectada como %s, ¿es necesario cambiarla? (y / n): "
is_need_to_type_proxy: "No se detectó la dirección proxy del sistema, ¿necesita configurarla manualmente? (y / n): "
login:
hint_intro_step_head: "[Iniciar sesión] Siga los pasos a continuación:"
Expand Down
7 changes: 3 additions & 4 deletions app/config/language/zh.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ app.core.biu:
success_to_login: "登录成功"
config:
hint_port_is_in_use: "现端口已被占用,请修改 config.yml 中的 sys.host 配置项"
hint_proxy_in_use: "已启用代理"
hint_proxy_in_use: "已启用代理 %s"
fail_to_load_config: "读取配置文件失败,程序无法正常运行"
outdated:
hint_latest: "最新"
Expand All @@ -16,7 +16,7 @@ app.core.biu:
network:
hint_in_check: "检测网络状态..."
fail_pixiv_and_use_bypass: "无法访问 Pixiv,启用 bypassSNI 线路 (可能无法正常使用)"
loginHelper:
login:
hint_token_only: "由于 Pixiv 禁止了账号密码登陆方式,目前只能使用 Token 进行登录"
hint_before_start: "即将开始进行网络检测,此过程可以减少因网络问题导致的无法正常使用 PixivBiu 的概率"
fail_to_get_token_due_to_network: "您的网络无法正常进行 Pixiv Token 登陆,请调整后重试"
Expand All @@ -37,9 +37,8 @@ app.core.biu:

app.common.loginHelper:
network:
hint_in_check: "检测网络状态..."
press_need_to_type_proxy: "请输入代理地址(可留空): "
hint_detect_proxy_and_continue: "检测到为 %s 的代理地址,是否继续? (y / n): "
hint_detect_proxy: "检测到为 %s 的代理地址,是否需要更改? (y / n): "
is_need_to_type_proxy: "未能检测到代理地址,是否需要手动设置? (y / n): "
login:
hint_intro_step_head: "[Login] 请按以下步骤进行操作:"
Expand Down
76 changes: 37 additions & 39 deletions app/lib/common/login_helper/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from altfe.interface.root import interRoot
from app.lib.common.login_helper.token import TokenGetter
from app.v2.utils.sprint import SPrint

_ln = lambda val, header="Login Helper": print(f"[{header}] " + val if header else val)

Expand All @@ -24,29 +25,26 @@ class CommonLoginHelper(interRoot):
def __init__(self):
self.lang = self.INS.i18n.get_bundle("app.common.loginHelper", func=True)
self.requests = requests.Session()
self.requests.mount("https://", CustomAdapter())
# self.requests.mount("https://", CustomAdapter())
self.token_getter = TokenGetter(lang=self.lang, requests=self.requests)
self.proxy = ""
self.auth_token_url = ""

def check_network(self, is_no_proxy: bool, silent=False):
def check_network(self, is_no_proxy: bool = False, is_silent: bool = False):
"""
网络检测。筛选出本机可通的 Pixiv API 服务器。
:param URLS: 全部 URL
:param silent: 是否静默进行
:param proxy_: 代理设置,auto 为程序自动判断
:return: bool
"""
if not silent:
_ln(self.lang("network.hint_in_check"))

# Determine the final proxy address, or empty
self.proxy = "" if is_no_proxy else self._determine_proxy(silent=silent)
self.proxy = "" if is_no_proxy else self._determine_proxy(is_silent=is_silent)

# Determine the final auth host
# Check if the hosts are accessible
is_conn_array = [
self._test_access(url=url, proxy=self.proxy, silent=silent)
self._test_access(url=url, proxy=self.proxy, is_silent=False)
for url in self.SOME_URLS
]

Expand Down Expand Up @@ -146,46 +144,46 @@ def get_proxy(self) -> str:
def is_bypass(self) -> bool:
return self.auth_token_url != self.SOME_URLS[0]

def _determine_proxy(self, silent: bool = False) -> str:
def _determine_proxy(self, is_silent: bool = False) -> str:
proxy = self.STATIC.util.get_system_proxy()
if proxy != "" and self._test_pixiv_connection(proxy=proxy):
pass
elif self._test_pixiv_connection(proxy=""):
proxy = ""
elif silent is False:
elif is_silent is False:
# Require to set proxy manually
if proxy != "":
if (
input(self.lang("network.hint_detect_proxy_and_continue") % proxy)
== "n"
):
proxy = input(self.lang("network.press_need_to_type_proxy"))
else:
if input(self.lang("network.is_need_to_type_proxy")) == "y":
proxy = input(self.lang("network.press_need_to_type_proxy"))
if input(
self.lang("network.hint_detect_proxy") % proxy
if proxy
else self.lang("network.is_need_to_type_proxy")
) in ["y", ""]:
proxy = input(self.lang("network.press_need_to_type_proxy"))
return proxy

@classmethod
def _test_access(cls, url: str, proxy: str = "", silent: bool = False):
def _test_access(cls, url: str, proxy: str = "", is_silent: bool = False):
"""
request get 请求。
:param url: URL
:param proxy: 代理,留空则不使用
:param silent: 是否静默运行
:return: bool
"""
is_ok = False
try:
if proxy != "":
requests.head(url, proxies={"http": proxy, "https": proxy}, timeout=3)
is_ok = True
else:
requests.head(url, timeout=3)
except:
if silent is False:
cls.STATIC.localMsger.red(f"{url} [ops]", header="Network")
return False
if silent is False:
cls.STATIC.localMsger.green(f"{url} [yep]", header="Network")
return True
pass
if not is_silent:
if is_ok:
_ln(SPrint.green(f"- {url} [yep]"), header=None)
else:
_ln(SPrint.red(f"- {url} [ops]"), header=None)
return is_ok

@classmethod
def _test_pixiv_connection(cls, proxy: str = "") -> bool:
Expand All @@ -197,19 +195,19 @@ def _test_pixiv_connection(cls, proxy: str = "") -> bool:
return True


class CustomAdapter(requests.adapters.HTTPAdapter):
"""
防止在请求 Cloudflare 时可能的 SSL 相关错误。
Thanks to @github/grawity.
"""
# class CustomAdapter(requests.adapters.HTTPAdapter):
# """
# 防止在请求 Cloudflare 时可能的 SSL 相关错误。
# Thanks to @github/grawity.
# """

def init_poolmanager(self, *args, **kwargs):
# When urllib3 hand-rolls a SSLContext, it sets 'options |= OP_NO_TICKET'
# and CloudFlare really does not like this. We cannot control this behavior
# in urllib3, but we can just pass our own standard context instead.
import ssl
# def init_poolmanager(self, *args, **kwargs):
# # When urllib3 hand-rolls a SSLContext, it sets 'options |= OP_NO_TICKET'
# # and CloudFlare really does not like this. We cannot control this behavior
# # in urllib3, but we can just pass our own standard context instead.
# import ssl

ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ctx.load_default_certs()
ctx.set_alpn_protocols(["http/1.1"])
return super().init_poolmanager(*args, **kwargs, ssl_context=ctx)
# ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
# ctx.load_default_certs()
# ctx.set_alpn_protocols(["http/1.1"])
# return super().init_poolmanager(*args, **kwargs, ssl_context=ctx)
Loading

0 comments on commit 6b6ea8d

Please sign in to comment.