Skip to content

Commit

Permalink
Merge pull request #73 from huajijam/main
Browse files Browse the repository at this point in the history
add features, fix typo,add gitignore and no pycache
  • Loading branch information
Samueli924 authored Apr 14, 2022
2 parents f9ac748 + 6fb1633 commit 96f8ad0
Show file tree
Hide file tree
Showing 10 changed files with 71 additions and 31 deletions.
3 changes: 3 additions & 0 deletions api/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
__pycache__/
*.py[cod]
*$py.class
Binary file removed api/__pycache__/__init__.cpython-39.pyc
Binary file not shown.
Binary file removed api/__pycache__/chaoxing.cpython-39.pyc
Binary file not shown.
7 changes: 5 additions & 2 deletions api/chaoxing.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@


class Chaoxing:
def __init__(self, usernm, passwd):
def __init__(self, usernm, passwd, debug):
self.usernm = usernm
self.passwd = passwd
self.logger = Logger("ChaoxingAPI")
self.logger = Logger("ChaoxingAPI",debug)
self.session = None
self.uid = None
self.cookies = None
Expand Down Expand Up @@ -44,7 +44,9 @@ def login(self):
"t": "true",
"forbidotherlogin": "0",
"validate": ""}
self.logger.debug("发送登录数据")
resp = self.session.post(url, data=data)
self.logger.debug("收到返回数据")
if resp.json()["status"]:
self.uid = resp.cookies['_uid']
self.cookies = dict_from_cookiejar(resp.cookies)
Expand All @@ -60,6 +62,7 @@ def status(self):
:return:
"""
if not re.findall("<title>用户登录</title>", self.session.get("https://i.chaoxing.com/base").text):
self.logger.debug("用户Cookies有效")
return True
else:
return False
Expand Down
38 changes: 27 additions & 11 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import random
import time
import argparse

import utils.functions as ft
from api.chaoxing import Chaoxing
Expand All @@ -10,7 +11,7 @@ def do_work(chaoxingAPI):
logger.info("开始获取所有章节")
chaoxingAPI.get_selected_course_data() # 读取所有章节
for mission in chaoxingAPI.missions:
# logger.info("开始读取章节信息")
logger.debug("开始读取章节信息")
knowledge_raw = chaoxingAPI.get_mission(mission['id'], chaoxingAPI.selected_course['key']) # 读取章节信息
if "data" not in knowledge_raw and "error" in knowledge_raw:
input("当前课程需要认证,请在学习通客户端中验证码认证后再运行本课程\n点击回车键退出程序")
Expand All @@ -36,7 +37,7 @@ def do_work(chaoxingAPI):
continue
print(f"\n当前视频:{attachment['property']['name']}")
if attachment.get('isPassed'):
print("当前视频任务过去已完成")
print("当前视频任务已完成")
ft.show_progress(attachment['property']['name'], 1, 1)
continue
video_info = chaoxingAPI.get_d_token(
Expand All @@ -62,21 +63,36 @@ def do_work(chaoxingAPI):


if __name__ == '__main__':
parser = argparse.ArgumentParser(description='chaoxing-xuexitong') # 命令行传参
parser.add_argument('-debug','--debug', action='store_true', help='Enable debug output in console')
parser.add_argument('--no-logo', action='store_false', help='Disable Boot logo')
parser.add_argument('--no-sec', action='store_false', help='Disable all security feature')

args = parser.parse_args() # 定义专用参数变量
debug = args.debug # debug输出 Default:False
logo = args.no_logo # 展示启动LOGO Default:True
hideinfo = args.no_sec # 启用隐私保护 Default:True

try:
ft.init_all_path(["saves", "logs"]) # 检查文件夹
logger = ft.Logger("main") # 初始化日志类
ft.title_show() # 显示头
logger.info("正在获取用户数据...")
usernm, passwd = ft.load_users() # 获取账号密码
chaoxing = Chaoxing(usernm, passwd) # 实例化超星API
logger = ft.Logger("main",debug) # 初始化日志类
if debug:
logger.debug("已启用debug输出")
ft.title_show(logo) # 显示头
if not logo:
logger.debug("已关闭启动LOGO")
logger.info("正在读取本地用户数据...")
usernm, secname, passwd = ft.load_users(hideinfo) # 获取账号密码
chaoxing = Chaoxing(usernm, passwd, debug) # 实例化超星API
chaoxing.init_explorer() # 实例化浏览Explorer
logger.info("开始登录")
logger.info("登陆中")
if chaoxing.login(): # 登录
logger.info("开始读取所有课程")
logger.info("已登录账户:" +secname)
logger.info("正在读取所有课程")
if chaoxing.get_all_courses(): # 读取所有的课程
logger.info("开始选课")
logger.info("进行选课")
if chaoxing.select_course(): # 选择要学习的课程
chaoxing.speed = int(input("当前倍速: 1 倍速 \n在不紧急的情况下建议使用 1 倍速,因使用不合理的多倍速造成的一切风险与作者无关\n请输入您想要的整数学习倍速:"))
chaoxing.speed = int(input("默认倍速: 1 倍速 \n在不紧急的情况下建议使用 1 倍速,因使用不合理的多倍速造成的一切风险与作者无关\n请输入您想要的整数学习倍速:"))
logger.info("开始学习")
do_work(chaoxing) # 开始学习
input("任务已结束,请点击回车键退出程序")
Expand Down
3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
maskpass
natsort
requests
urllib3==1.25.11
urllib3==1.25.11
3 changes: 3 additions & 0 deletions utils/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
__pycache__/
*.py[cod]
*$py.class
Binary file removed utils/__pycache__/__init__.cpython-39.pyc
Binary file not shown.
Binary file removed utils/__pycache__/functions.cpython-39.pyc
Binary file not shown.
48 changes: 31 additions & 17 deletions utils/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,18 @@
import logging
import os
import time
import maskpass
from hashlib import md5
from os import mkdir
from os.path import exists
import random
from natsort import natsorted


def title_show():
print("-"*120 + "\n")
print(""" ,---.-, ,--,
def title_show(logo):
if logo:
print("-"*120 + "\n")
print(""" ,---.-, ,--,
.--.--. ____ ,--, ' ,' '. ,----, ,--.'|
/ / '. ,' , `. ,--.'| ,--, / / \ .' .' \ ,--, | :
| : /`. / ,-+-,.' _ | ,--, | | : ,--.'|. ; ,/. : ,----,' |,---.'| : '
Expand All @@ -25,9 +27,11 @@ def title_show():
`--'---' ; : .' \| ;/ : , .-./| : || , / ; : ; | | '| : .' | : ;
| , .-./'---' `--`----' \ \ / ---`-' | , / ; |.' ; | .' ' ,/
`--`---' `----' ---`-' '---' `---' '--' """)
print("\n" + "-"*120)
print("\n" + "-"*120)
else:
print("\n")
print("欢迎使用Samueli924/chaoxing\n对代码有任何疑问或建议,请前往https://github.com/Samueli924/chaoxing进行反馈")
print("如果喜欢这段代码,请给我的repo一个小小的Star,谢谢\n")
print("如果喜欢这个项目,请给我的repo一个小小的Star,谢谢\n")


def check_path(path: str, file: bool = True):
Expand Down Expand Up @@ -58,24 +62,24 @@ def init_all_path(init_path):


class Logger:
def __init__(self, name, show=True, save=True, debug=False):
def __init__(self, name, debug, show=True, save=True ):
"""
日志记录系统
:param name: 日志保存时使用的Name
:param debug: 控制台输出等级传参
:param show: 是否在控制台显示日志
:param save: 是否将日志保存至本地
:param debug: 是否开启DEBUG模式
"""
log_path = f"logs/{name}.log"
self.logger = logging.getLogger(name)
# self.logger.handlers.clear()
self.logger.setLevel(logging.DEBUG)
if show:
sh = logging.StreamHandler()
# if debug:
# sh.setLevel(logging.DEBUG)
# else:
sh.setLevel(logging.INFO)
if debug:
sh.setLevel(logging.DEBUG)
else:
sh.setLevel(logging.INFO)
sh.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
self.logger.addHandler(sh)
if save:
Expand Down Expand Up @@ -108,26 +112,36 @@ def save_users(usernm, passwd):
return True


def load_users():
def load_users(hide):
if os.listdir("saves"):
users = os.listdir("saves")
print("-" * 40)
for index, user in enumerate(users):
print(f"{index + 1}. {user}")
if hide:
sec_user = "%s****%s"%(user[:3],user[7:])
else:
sec_user = user
print(f"{index + 1}. {sec_user}")
print("-" * 40)
num = input("请输入要登录的用户序号,新建请输入直接点击回车键")
num = input("请输入要登录的用户序号,新建用户请直接点击回车键")
if not num:
usernm = input("请输入手机号")
passwd = input("请输入密码")
if hide:
passwd = maskpass.askpass(prompt="请输入密码(已自动隐藏)", mask="#")
else:
passwd = input("请输入密码")
else:
with open(f"saves/{users[int(num) - 1]}/user.json", "r") as f:
__temp = json.loads(f.read())
usernm = __temp["usernm"]
passwd = __temp["passwd"]
else:
usernm = input("请输入手机号")
passwd = input("请输入密码")
return usernm, passwd
if hide:
passwd = passwd = maskpass.askpass(prompt="请输入密码(已自动隐藏)", mask="#")
else:
passwd = input("请输入密码")
return usernm, sec_user, passwd


def load_finished(usernm):
Expand Down

0 comments on commit 96f8ad0

Please sign in to comment.