def __Init_Task(cls) -> None: """ 任务表初始化(不为空的时候) :return: None """ if DB_MANAGE().Task.Empty(): html = REQUESTS.Get(url=API().Task_Parent.geturl()) parent = html.json() for key in parent.keys(): son = API().Task_Son.geturl().format(channel_id=key) task = TASK(link=son, isread=False) DB_MANAGE().Task.Insert(task=task)
def _Login(self) -> bool: """ _Login() -> Bool 进行登录; 具体流程: 1、开启循环检测二维码状态 1、获取二维码图片 2、显示二维码 3、二维码状态检测 4、根据3的返回值决定: 1、刷新二维码,中断本次循环,再来一次 2、提取Token值,根据选项(持久化)决定是否保持token,关闭二维码容器 :return: Bool,返回值只有True,如未登录则会一直循环 """ self.__network.Clear() self.__driver.get(url=API().Login.geturl()) while True: qr = self.__Get_QR() QR_VESSEL().Show_QR(qr=qr) status = self.__Check_Status() if not status: self.__QR_Refresh() continue else: while self.__driver.current_url != API().Master.geturl(): continue cookies = self.__driver.get_cookies() token = [{cookie['name']: cookie['value']} for cookie in cookies if cookie['name'] == 'token'] if token: INFO_MANAGE().Init(token=token[0]['token']) if OPTIONS().Token: cookie = token[0] html = REQUESTS().Get( url=API().Aggregate_Score.geturl(), cookies=cookie ) data = html.json() user_id = data['data']['userId'] user = USER(user_id=user_id, token=token[0]['token']) if DB_MANAGE().User.Exist_User(user=user): DB_MANAGE().User.Update(user=user) else: DB_MANAGE().User.Insert(user=user) DB_MANAGE().Article.Update_All() DB_MANAGE().Video.Update_All() QR_VESSEL().QR_QUIT() return status
def __Check(self, item: str, tq: int) -> None: """ __Check(item: str, tq: int) -> None 监测任务的完成 :param item: 任务编号 :param tq: 等待程度 :return: None """ bar = tqdm(desc=item, total=tq, unit='it', leave=False, ncols=70) count = 0 start = time.time() while True: js = "document.documentElement.scrollTop={speed}" self.__driver.execute_script(script=js.format( speed=RANDOM.Int(a=1, b=10))) temp = self.__network.Get() if API().Task_Check.geturl() in temp.keys() or \ time.time() - start >= 35: count += 1 bar.update(n=1) start = time.time() if count >= tq: break time.sleep(0.1) bar.close()
def __Driver_Check(self) -> None: """ __Driver_Check() -> None 驱动检查,确保驱动能够正常使用 :return: None """ temp = False if not temp and not self.__Check_Dir(): temp = True if not temp and not DRIVER_CHECK().File: print(f"检测到驱动未下载") temp = True if not temp and not DRIVER_CHECK().Driver_Chrome_Version( system=SYSTEM()): print(f"检测到驱动不支持本机Chrome") temp = True if temp: print(f"驱动自动下载中") size = DRIVER_DOWNLOAD().Download( link=API().Driver.Download(system=SYSTEM())) print(f"驱动自动下载完毕\n" f"文件大小为{size / 1024 / 1024}MB") if not DRIVER_CHECK().Execute_Permission: print(f"检测到驱动没有执行权限\n" f"自动添加执行权限") DRIVER_CHECK().Add_Execute_Permission(system=SYSTEM()) print(f"添加执行权限完毕")
def __Get_QR_Status_Network(self, key: str, value: str) -> int: """ __Get_QR_Status_Network(key: str, value: str) -> int 获取二维码状态码(Network中获取) :param key: url :param value: requestId :return: int -1: 还未请求 1: 成功 11021: 未登录 11019: 二维码失效 """ if API().Login_QR_Status.geturl() == key: while True: try: response = self.__network.GetResponseBody(requestId=value) response = json.loads(response['body']) if response['success']: return 1 else: return int(response['code']) except WebDriverException: continue return -1
def Get_Task_Bar(self) -> None: """ Get_Task_Bar() -> None 获取任务进度 :return: None """ while True: try: html = REQUESTS().Get(url=API().Task_Bar.geturl(), cookies=self.__cookie) data = html.json() for rule in data['data']['dayScoreDtos']: task = self.__info.Task_Bar.get(rule['ruleId']) if not task: ruleId = rule['ruleId'] name = rule['name'] desc = rule['desc'] currentScore = rule['currentScore'] dayMaxScore = rule['dayMaxScore'] task = TASK_INFO(ruleId=ruleId, name=name, desc=desc, currentScore=currentScore, dayMaxScore=dayMaxScore) else: task.Current_Score = rule['currentScore'] self.__info.Update_Task_Bar_Info(task_info=task) break except TypeError: continue
def __Check_Project_Answer(self) -> None: """ __Check_Project_Answer() -> None 监测专项答题任务的完成 :return: None """ while True: bar = INFO_MANAGE().Task_Bar if bar[4].Current_Score != bar[4].Day_Max_Score: if self.__answer_time[-1]: if time.time() - self.__answer_time[0] <= 10: continue token = self.__driver.get_cookie(name='token')['value'] iid = TASK_INIT().Assigning_Project_Answer(token=token) if not iid: print("没有专项答题任务了") break temp = TASK_ANSWER(driver=self.__driver) try: temp.Do(link=API().Project_Answer_Topic.geturl().format(num=iid)) except TASK_EXCEPTION: DB_MANAGE().Project.Insert(PROJECT(pid=iid)) OUTPUT.Info() self.__answer_time = (time.time(), True) else: break
def __Accomplish(self) -> bool: """ __Accomplish() -> bool 检测答题是否完成 :return: bool """ while True: for key, value in self.__network.Get().items(): if re.match(pattern=API().Answer_Accomplish.geturl(), string=key): return True
def __Get_QR_ID(self, key: str, value: str) -> str: """ __Get_QR_ID(key: str, value: str) -> str 获取二维码ID,格式为:qr:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx :param key: url :param value: requestId :return: str """ if API().Login_Generate.geturl() == key: response = self.__network.GetResponseBody(requestId=value)[ 'body'] response = json.loads(response) return response['result'] return ''
def Login(self) -> bool: """ Login() -> bool 登录,如果user表不为空会检测令牌是否有效,有效则直接登录 :return: bool """ if DB_MANAGE().User.Exist(): user = DB_MANAGE().User.Query() if CHECK_TOKEN.Check_Token(token=user.Token): INFO_MANAGE().Init(token=user.Token) self.__driver.get(url=API().Master.geturl()) self.__driver.add_cookie(cookie_dict=user.Token_Driver) self.__driver.refresh() return True return self._Login()
def __Get_QR_State(self, key: str) -> str: """ __Get_QR_State(key: str) -> str 获取二维码的state,在iframe链接中提取 :param key: iframe链接 :return: str """ temp = re.match( pattern=API().Login_QR_Iframe.geturl(), string=key ) if temp: url = parse.urlparse(url=key) return parse.parse_qs(qs=url.query)['state'][0] return ''
def Get_Daily_Score(self) -> None: """ Get_Daily_Score() -> None 获取每日积分 :return: None """ while True: try: html = REQUESTS().Get(url=API().Daily_Score.geturl(), cookies=self.__cookie) data = html.json() self.__info.Daily_Score = data['data']['score'] break except TypeError: continue
def _Init_Info(self) -> None: """ _Init_Info() -> None 初始化用户id :return: None """ while True: try: html = REQUESTS().Get(url=API().Aggregate_Score.geturl(), cookies=self.__cookie) data = html.json() self.__info.User_Id = data['data']['userId'] break except TypeError: continue
def Assigning_Project_Answer(self, token: str) -> int: """ Assigning_Project_Answer(token: str) -> int 获取最早且未过期的专项答题任务ID :param token: 令牌 :return: int """ cookie = {'token': token} for num in range(5, 0, -1): html = REQUESTS.Get( url=API().Project_Answer_Topics.geturl().format(num=num), cookies=cookie) data = html.json() data = json.loads( base64.b64decode(data['data_str']).decode('utf-8')) for topic in data['list'][::-1]: if (not topic['overdue']) and (not topic['seeSolution']): return topic['id']
def Get_Level(self) -> None: """ Get_Level() -> None 获取等级 :return: None """ while True: try: html = REQUESTS().Get(url=API().Level.geturl(), cookies=self.__cookie) data = html.json() self.__info.Level = data['data']['level'] self.__info.Level_Name = data['data']['levelName'] self.__info.Rank_Accumulate_In_Country = \ data['data']['rankAccumulateInCountry'] break except TypeError: continue
def __Check_Daily_Answer(self) -> None: """ __Check_Daily_Answer() -> None 监测每日答题任务的完成 :return: None """ while True: bar = INFO_MANAGE().Task_Bar if bar[6].Current_Score != bar[6].Day_Max_Score: if self.__answer_time[-1]: if time.time() - self.__answer_time[0] <= 10: continue temp = TASK_ANSWER(driver=self.__driver) temp.Do(link=API().Daily_Answer.geturl()) OUTPUT.Info() self.__answer_time = (time.time(), True) else: break
def Assigning_Weekly_Answer(self, token: str) -> int: """ Assigning_Weekly_Answer(token: str) -> int 获取本周最早且未做的每周答题任务ID :param token: 令牌 :return: int """ cookie = {'token': token} for num in range(3, 0, -1): html = REQUESTS.Get( url=API().Weekly_Answer_Topics.geturl().format(num=num), cookies=cookie) data = html.json() data = json.loads( base64.b64decode(data['data_str']).decode('utf-8')) for group in data['list'][::-1]: for practice in group['practices'][::-1]: if not practice['seeSolution']: return practice['id']
def __Change_Driver_Cookie(self, key: str, state: str) -> None: """ __Change_Driver_Cookie(key: str, state: str) -> None 此处是应对network中还未查询二维码状态时,所做的措施,用处是加快登录过程,而不需要浏览器 自主添加cookie :param key: 最后一次查询二维码状态的api会返回code(只会允许查询一次,随后就是过期) :param state: iframe链接中提取 :return: None """ url = parse.urlparse(url=key) code = parse.parse_qs(qs=url.query)['loginTmpCode'][0] html = REQUESTS.Get( url=API().Login_Token.geturl().format(code=code, state=state) ) token = html.cookies.get(name='token') cookie = {'domain': '.xuexi.cn', 'name': 'token', 'value': token} self.__driver.add_cookie(cookie_dict=cookie) self.__driver.refresh()
def __Get_QR_Status_Requests(self, qr_data: Dict, qr_state: str): """ __Get_QR_Status_Requests(qr_data: Dict) -> int 获取二维码状态码(requests请求) :param qr_data: 带有二维码编号的data :param qr_state: 二维码的state :return: int 1: 成功 11021: 未登录 11019: 二维码失效 """ html = REQUESTS.Post( url=API().Login_QR_Status.geturl(), data=qr_data ) status = html.json() if status['success']: self.__Change_Driver_Cookie(key=status['data'], state=qr_state) return 1 else: return int(status['code'])