Skip to content

Commit

Permalink
chore: update error log
Browse files Browse the repository at this point in the history
  • Loading branch information
yanglbme committed Dec 12, 2023
1 parent c82c35c commit 085e5d4
Show file tree
Hide file tree
Showing 6 changed files with 172 additions and 125 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ Run yanglbme/gitee-pages-action@main
| 2 | Error: Need captcha validation, please visit https://gitee.com/login, login to validate your account. | 需要图片验证码校验。可以手动登录 Gitee 官方,校验验证码。 |
| 3 | Error: Need phone captcha validation, please follow wechat official account "Gitee" to bind account to turn off authentication. | 需要短信验证码校验。可以关注 Gitee 微信公众号,并绑定 Gitee 帐号,接收登录提示。[#6](https://github.com/yanglbme/gitee-pages-action/issues/6) |
| 4 | Error: Do not deploy frequently, try again one minute later. | 短期内频繁部署 Gitee Pages 导致,可以稍后再触发自动部署。 |
| 5 | Error: Deploy error occurred, please check your input `gitee-repo`. | `gitee-repo` 参数格式如:`doocs/leetcode`,并且严格区分大小写,请准确填写。[#10](https://github.com/yanglbme/gitee-pages-action/issues/10) |
| 5 | Error: Deploy error occurred, please re-run job or check your input `gitee-repo`. | `gitee-repo` 参数格式如:`doocs/leetcode`,并且严格区分大小写,请准确填写。[#10](https://github.com/yanglbme/gitee-pages-action/issues/10) |
| 6 | Error: Unknown error occurred in login method, resp: ... | 登录出现未知错误,请在 [issues](https://github.com/yanglbme/gitee-pages-action/issues) 区反馈。 |
| 7 | Error: Rebuild page error, status code: xxx | 更新 Pages 时状态码异常,请尝试再次触发 Action 执行。也可能为 gitee pages 未初始化,第一次需要手动部署 gitee pages。 |
| 8 | Error: HTTPSConnectionPool(host='gitee.com', port=443): Read timed out. (read timeout=6)<br><br>Error: HTTPSConnectionPool(host='gitee.com', port=443): Max retries exceeded with url: /login (Caused by ConnectTimeoutError(<urllib3.connection.HTTPSConnection object at 0x7f6c889d42e8>, 'Connection to gitee.com timed out. (connect timeout=6)')) | 网络请求出错,请尝试 Re-run jobs 。[#27](https://github.com/yanglbme/gitee-pages-action/issues/27) |
Expand Down
220 changes: 133 additions & 87 deletions app/action.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,20 @@


class Action:
def __init__(self, username: str, password: str,
repo: str, branch: str = 'master',
directory: str = '', https: str = 'true'):
def __init__(
self,
username: str,
password: str,
repo: str,
branch: str = "master",
directory: str = "",
https: str = "true",
):
self.session = requests.session()
self.session.keep_alive = False
self.username = username
self.password = password
self.repo = repo.replace(domain, '').strip('/')
self.repo = repo.replace(domain, "").strip("/")
self.branch = branch
self.directory = directory
self.https = https
Expand All @@ -29,138 +35,178 @@ def __init__(self, username: str, password: str,
def get_csrf_token(html: str) -> str:
res1 = re.search(
'<meta name="csrf-param" content="authenticity_token" />(.*?)'
'<meta name="csrf-token" content="(.*?)" />', html, re.S)
'<meta name="csrf-token" content="(.*?)" />',
html,
re.S,
)
res2 = re.search(
'<meta content="authenticity_token" name="csrf-param" />(.*?)'
'<meta content="(.*?)" name="csrf-token" />', html, re.S)
'<meta content="(.*?)" name="csrf-token" />',
html,
re.S,
)
res = res1 or res2
if res is None:
raise Exception('Deploy error occurred, please check your input `gitee-repo`.')
raise Exception(
"Deploy error occurred, please re-run job or check your input `gitee-repo`."
)
return res.group(2)

@retry((requests.exceptions.ReadTimeout,
@retry(
(
requests.exceptions.ReadTimeout,
requests.exceptions.ConnectTimeout,
requests.exceptions.ConnectionError,
requests.Timeout,
requests.RequestException),
tries=4, delay=2, backoff=3)
requests.RequestException,
),
tries=4,
delay=2,
backoff=3,
)
def login(self):
login_index_url = f'{domain}/login'
check_login_url = f'{domain}/check_user_login'
form_data = {'user_login': self.username}
login_index_url = f"{domain}/login"
check_login_url = f"{domain}/check_user_login"
form_data = {"user_login": self.username}

index_headers = {
'Accept': 'text/html,application/xhtml+xml,application/xml;'
'q=0.9,image/webp,image/apng,*/*;'
'q=0.8,application/signed-exchange;v=b3;q=0.9',
'Host': 'gitee.com',
'User-Agent': ua
"Accept": "text/html,application/xhtml+xml,application/xml;"
"q=0.9,image/webp,image/apng,*/*;"
"q=0.8,application/signed-exchange;v=b3;q=0.9",
"Host": "gitee.com",
"User-Agent": ua,
}

resp = self.session.get(url=login_index_url,
headers=index_headers,
timeout=timeout,
verify=False)
resp = self.session.get(
url=login_index_url, headers=index_headers, timeout=timeout, verify=False
)
csrf_token = Action.get_csrf_token(resp.text)
headers = {
'Referer': login_index_url,
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-Token': csrf_token,
'User-Agent': ua
"Referer": login_index_url,
"X-Requested-With": "XMLHttpRequest",
"X-CSRF-Token": csrf_token,
"User-Agent": ua,
}
self.session.post(url=check_login_url,
headers=headers,
data=form_data,
timeout=timeout,
verify=False)
self.session.post(
url=check_login_url,
headers=headers,
data=form_data,
timeout=timeout,
verify=False,
)

# https://assets.gitee.com/assets/encrypt.js
separator = '$gitee$'
data = f'{csrf_token[-8:]}{separator}{self.password}'
separator = "$gitee$"
data = f"{csrf_token[-8:]}{separator}{self.password}"
pk = rsa.PublicKey.load_pkcs1_openssl_pem(pubkey.encode())
encrypt_data = rsa.encrypt(data.encode(), pk)
encrypt_data = base64.b64encode(encrypt_data).decode()

form_data = {
'encrypt_key': 'password',
'utf8': '✓',
'authenticity_token': csrf_token,
'redirect_to_url': '',
'user[login]': self.username,
'encrypt_data[user[password]]': encrypt_data,
'user[remember_me]': 1
"encrypt_key": "password",
"utf8": "✓",
"authenticity_token": csrf_token,
"redirect_to_url": "",
"user[login]": self.username,
"encrypt_data[user[password]]": encrypt_data,
"user[remember_me]": 1,
}
res = self.session.post(url=login_index_url,
headers=index_headers,
data=form_data,
timeout=timeout,
verify=False).text

case1 = ['"message": "帐号或者密码错误"', '"message": "Invalid email or password."',
'"message": "not_found_in_database"', '"message": "not_found_and_show_captcha"']
res = self.session.post(
url=login_index_url,
headers=index_headers,
data=form_data,
timeout=timeout,
verify=False,
).text

case1 = [
'"message": "帐号或者密码错误"',
'"message": "Invalid email or password."',
'"message": "not_found_in_database"',
'"message": "not_found_and_show_captcha"',
]
case2 = ['"message": "captcha_expired"', '"message": "captcha_fail"']
case3 = ['"message": "phone_captcha_fail"', '当前帐号存在异常登录行为,为确认你的有效身份',
'一条包含验证码的信息已发送至你的', 'A message containing a verification code has been sent to you']
case4 = ['个人主页', '我的工作台', '我的工作臺', 'Dashboard - Gitee']
case3 = [
'"message": "phone_captcha_fail"',
"当前帐号存在异常登录行为,为确认你的有效身份",
"一条包含验证码的信息已发送至你的",
"A message containing a verification code has been sent to you",
]
case4 = ["个人主页", "我的工作台", "我的工作臺", "Dashboard - Gitee"]

if any(e in res for e in case1):
raise Exception('Wrong username or password, login failed.')
raise Exception("Wrong username or password, login failed.")
if any(e in res for e in case2):
raise Exception('Need captcha validation, please visit '
'https://gitee.com/login, login to validate your account.')
raise Exception(
"Need captcha validation, please visit "
"https://gitee.com/login, login to validate your account."
)
if any(e in res for e in case3):
raise Exception('Need phone captcha validation, please follow wechat '
'official account "Gitee" to bind account to turn off authentication.')
raise Exception(
"Need phone captcha validation, please follow wechat "
'official account "Gitee" to bind account to turn off authentication.'
)
if not any(e in res for e in case4):
raise Exception(f'Unknown error occurred in login method, resp: {res}')
raise Exception(f"Unknown error occurred in login method, resp: {res}")

@retry((requests.exceptions.ReadTimeout,
@retry(
(
requests.exceptions.ReadTimeout,
requests.exceptions.ConnectTimeout,
requests.exceptions.ConnectionError,
requests.Timeout,
requests.RequestException),
tries=4, delay=2, backoff=3)
requests.RequestException,
),
tries=4,
delay=2,
backoff=3,
)
def rebuild_pages(self):
if '/' not in self.repo:
self.repo = f'{self.username}/{self.repo}'
if "/" not in self.repo:
self.repo = f"{self.username}/{self.repo}"

pages_url = f'{domain}/{self.repo}/pages'
rebuild_url = f'{pages_url}/rebuild'
pages_url = f"{domain}/{self.repo}/pages"
rebuild_url = f"{pages_url}/rebuild"

pages = self.session.get(pages_url)
csrf_token = Action.get_csrf_token(pages.text)
headers = {
'Content-Type': 'application/x-www-form-urlencoded; '
'charset=UTF-8',
'Referer': pages_url,
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-Token': csrf_token,
'User-Agent': ua
"Content-Type": "application/x-www-form-urlencoded; " "charset=UTF-8",
"Referer": pages_url,
"X-Requested-With": "XMLHttpRequest",
"X-CSRF-Token": csrf_token,
"User-Agent": ua,
}
form_data = {
'branch': self.branch,
'build_directory': self.directory,
'force_https': self.https
"branch": self.branch,
"build_directory": self.directory,
"force_https": self.https,
}
resp = self.session.post(url=rebuild_url,
headers=headers,
data=form_data,
timeout=timeout,
verify=False)
resp = self.session.post(
url=rebuild_url,
headers=headers,
data=form_data,
timeout=timeout,
verify=False,
)
if resp.status_code != 200:
raise Exception(f'Rebuild page error, status code: {resp.status_code}, resp: {resp.text}')
raise Exception(
f"Rebuild page error, status code: {resp.status_code}, resp: {resp.text}"
)
html = resp.text
if '正在部署,请耐心等待' in html:
if "正在部署,请耐心等待" in html:
return
if '部署失败' in html and '错误信息' in html:
res = re.search('<p>错误信息:(.*?)<\\\/p>', html, re.S)
if "部署失败" in html and "错误信息" in html:
res = re.search("<p>错误信息:(.*?)<\\\/p>", html, re.S)
if res:
raise Exception(res.group(1).strip())
if '请勿频繁更新部署,稍等1分钟再试试看' in html:
raise Exception('Do not deploy frequently, try again one minute later.')
if '仓库持有者未实名认证,不允许部署 pages 服务' in html:
raise Exception('The repository owner is not authenticated and is not allowed to deploy pages services.')
log.warning(f'Unknown html: {html}')
if "请勿频繁更新部署,稍等1分钟再试试看" in html:
raise Exception("Do not deploy frequently, try again one minute later.")
if "仓库持有者未实名认证,不允许部署 pages 服务" in html:
raise Exception(
"The repository owner is not authenticated and is not allowed to deploy pages services."
)
log.warning(f"Unknown html: {html}")

def run(self):
self.login()
Expand Down
8 changes: 5 additions & 3 deletions app/const.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
timeout = 6
domain = 'https://gitee.com'
domain = "https://gitee.com"

ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' \
'(KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36'
ua = (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36"
)

pubkey = """-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDIrn+WB2Yi4ABAL5Tq6E09tumY
Expand Down
18 changes: 9 additions & 9 deletions app/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,20 @@

def now():
tz = timezone(timedelta(hours=+8))
return datetime.now(tz).strftime('%Y-%m-%d %H:%M:%S')
return datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")


def info(s: str = ''):
core.info(f'[{now()}] {s}')
def info(s: str = ""):
core.info(f"[{now()}] {s}")


def warning(s: str = ''):
core.warning(f'[{now()}] {s}')
def warning(s: str = ""):
core.warning(f"[{now()}] {s}")


def error(s: str = ''):
core.info(f'[{now()}] {s}')
def error(s: str = ""):
core.info(f"[{now()}] {s}")


def set_failed(s: str = ''):
core.set_failed(f'[{now()}] {s}')
def set_failed(s: str = ""):
core.set_failed(f"[{now()}] {s}")
33 changes: 16 additions & 17 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,33 +3,32 @@
from app import log
from app.action import Action

author = {
'name': 'Yang Libin',
'link': 'https://github.com/yanglbme'
}
marketplace = 'https://github.com/marketplace/actions/gitee-pages-action'
author = {"name": "Yang Libin", "link": "https://github.com/yanglbme"}
marketplace = "https://github.com/marketplace/actions/gitee-pages-action"

log.info(f'Welcome to use Gitee Pages Action ❤\n\n'
f'📕 Getting Started Guide: {marketplace}\n'
f'📣 Maintained by {author["name"]}: {author["link"]}\n')
log.info(
f"Welcome to use Gitee Pages Action ❤\n\n"
f"📕 Getting Started Guide: {marketplace}\"
f'📣 Maintained by {author["name"]}: {author["link"]}\n
')

try:
username = core.get_input('gitee-username', required=True)
password = core.get_input('gitee-password', required=True)
repo = core.get_input('gitee-repo', required=True)
username = core.get_input("gitee-username", required=True)
password = core.get_input("gitee-password", required=True)
repo = core.get_input("gitee-repo", required=True)

branch = core.get_input('branch')
directory = core.get_input('directory')
https = core.get_input('https')
branch = core.get_input("branch")
directory = core.get_input("directory")
https = core.get_input("https")

action = Action(username, password, repo, branch, directory, https)

action.login()
log.info('Login successfully')
log.info("Login successfully")

action.rebuild_pages()
log.info('Rebuild Gitee Pages successfully')
log.info("Rebuild Gitee Pages successfully")

log.info('Success, thanks for using @yanglbme/gitee-pages-action!')
log.info("Success, thanks for using @yanglbme/gitee-pages-action!")
except Exception as e:
log.set_failed(str(e))
Loading

0 comments on commit 085e5d4

Please sign in to comment.