# Path: config/base_settings.py
# CAPTCHA_MODEL_NAME = os.path.join(BASE_PATH, 'res', 'captcha', 'sipo3.job')
# 
# TIMEOUT = 10
# 
# USE_PROXY = False
# 
# Path: controller/url_config.py

# 
# Path: service/proxy.py
# def update_proxy():
#     """
#     获取并校验代理ip地址
#     :return:
#     """
#     if bs.USE_PROXY:
#         i = 0
#         while True:
#             try:
#                 get_proxy()
#                 notify_ip_address()
#                 return True
#             except Exception:
#                 i += 1
#                 logger.error("代理获取失败，尝试重试，重试次数%s" % (i, ))
#     else:
#         logger.info('notify address')
#         notify_ip_address()
# 
# def notify_ip_address():
#     """
#     通知专利网我们的ip地址，
#     这个网站比较特别，每当有陌生ip地址时，都需要通过这个方法向网站发送一次请求先。
#     :return:
#     """
#     resp = requests.post(url_pre_execute.get('url'), proxies=ctrl.PROXIES, timeout=bs.TIMEOUT, cookies=ctrl.COOKIES)
#     # logger.debug(resp.text)
#     ip_address = json.loads(resp.text)
#     if ctrl.PROXIES is not None:
#         if ip_address.get('IP') == ctrl.PROXIES.get('http').split(':')[0]:
#             return resp.text
#         else:
#             raise Exception('ip error')
#     else:
#         return resp.text
# 
# def update_cookies(cookies=None):
#     """
#     更新或获取cookies
#     :param cookies:
#     :return:
#     """
#     if cookies is None:
#         ctrl.COOKIES = requests.get(url=url_index.get('url'), proxies=ctrl.PROXIES, timeout=bs.TIMEOUT).cookies
# 
#     else:
#         ctrl.COOKIES = cookies
# 
#     logger.info(ctrl.COOKIES)
#     if len(ctrl.COOKIES) == 0:
#         logger.error('cookie有问题')
#         raise ReadTimeout('cookie有问题')
# 
# Path: service/sipoknn.py
# def get_captcha_result(model_path, filename):
#     """
#     验证码解析
#     :param model_path: 之前训练的模型位置
#     :param filename: 需要解析的验证码全路径
#     :return: 解析结果
#     """
#     image = np.asarray(Image.open(filename).convert('L'))
#     image = (image > 135) * 255
#     letters = [image[:, 6:18].reshape(20 * 12), image[:, 19:31].reshape(20 * 12), image[:, 33:45].reshape(20 * 12),
#                image[:, 45:57].reshape(20 * 12)]
#     model = joblib.load(model_path)
#     result = ''
#     for c in model.predict(letters):
#         result += c
#     return eval(result)


import base64
import configparser
import click
import requests
import controller as ctrl
from logbook import *
from config.base_settings import CAPTCHA_MODEL_NAME, TIMEOUT, USE_PROXY
from controller.url_config import url_captcha, url_login
from service.proxy import update_proxy, notify_ip_address, update_cookies
from service.sipoknn import get_captcha_result
        ctrl.BEING_LOG = False
        return True

    error_times = 0
    while True:
        try:
            # logger.debug("before proxy")
            update_proxy()
            # logger.debug("before cookie")
            update_cookies()
            # logger.debug("after cookie")
            busername = change_to_base64(username)
            bpassword = change_to_base64(password)
            captcha = get_captcha()
            logger.info('验证码识别结果：%s' % captcha)
            form_data = url_login.get('form_data')
            form_data.__setitem__('j_validation_code', captcha)
            form_data.__setitem__('j_username', busername)
            form_data.__setitem__('j_password', bpassword)

            resp = requests.post(url=url_login.get('url'), headers=url_login.get('headers'), data=form_data,
                                 cookies=ctrl.COOKIES, proxies=ctrl.PROXIES, timeout=TIMEOUT)
            if resp.text.find(username + '，欢迎访问') != -1:
                # 网站调整了逻辑，下面这句不用了
                # print(resp.cookies)
                # ctrl.COOKIES.__delitem__('IS_LOGIN')
                # ctrl.COOKIES.set('IS_LOGIN', 'true', domain='www.pss-system.gov.cn/sipopublicsearch/patentsearch')
                jsession = ctrl.COOKIES.get('JSESSIONID')
                resp.cookies.__delitem__('JSESSIONID')
                resp.cookies.set('JSESSIONID', jsession, domain='www.pss-system.gov.cn')

# Path: config/base_settings.py
# CAPTCHA_MODEL_NAME = os.path.join(BASE_PATH, 'res', 'captcha', 'sipo3.job')
# 
# TIMEOUT = 10
# 
# USE_PROXY = False
# 
# Path: controller/url_config.py

# 
# Path: service/proxy.py
# def update_proxy():
#     """
#     获取并校验代理ip地址
#     :return:
#     """
#     if bs.USE_PROXY:
#         i = 0
#         while True:
#             try:
#                 get_proxy()
#                 notify_ip_address()
#                 return True
#             except Exception:
#                 i += 1
#                 logger.error("代理获取失败，尝试重试，重试次数%s" % (i, ))
#     else:
#         logger.info('notify address')
#         notify_ip_address()
# 
# def notify_ip_address():
#     """
#     通知专利网我们的ip地址，
#     这个网站比较特别，每当有陌生ip地址时，都需要通过这个方法向网站发送一次请求先。
#     :return:
#     """
#     resp = requests.post(url_pre_execute.get('url'), proxies=ctrl.PROXIES, timeout=bs.TIMEOUT, cookies=ctrl.COOKIES)
#     # logger.debug(resp.text)
#     ip_address = json.loads(resp.text)
#     if ctrl.PROXIES is not None:
#         if ip_address.get('IP') == ctrl.PROXIES.get('http').split(':')[0]:
#             return resp.text
#         else:
#             raise Exception('ip error')
#     else:
#         return resp.text
# 
# def update_cookies(cookies=None):
#     """
#     更新或获取cookies
#     :param cookies:
#     :return:
#     """
#     if cookies is None:
#         ctrl.COOKIES = requests.get(url=url_index.get('url'), proxies=ctrl.PROXIES, timeout=bs.TIMEOUT).cookies
# 
#     else:
#         ctrl.COOKIES = cookies
# 
#     logger.info(ctrl.COOKIES)
#     if len(ctrl.COOKIES) == 0:
#         logger.error('cookie有问题')
#         raise ReadTimeout('cookie有问题')
# 
# Path: service/sipoknn.py
# def get_captcha_result(model_path, filename):
#     """
#     验证码解析
#     :param model_path: 之前训练的模型位置
#     :param filename: 需要解析的验证码全路径
#     :return: 解析结果
#     """
#     image = np.asarray(Image.open(filename).convert('L'))
#     image = (image > 135) * 255
#     letters = [image[:, 6:18].reshape(20 * 12), image[:, 19:31].reshape(20 * 12), image[:, 33:45].reshape(20 * 12),
#                image[:, 45:57].reshape(20 * 12)]
#     model = joblib.load(model_path)
#     result = ''
#     for c in model.predict(letters):
#         result += c
#     return eval(result)


# Path: service/account.py
import base64
import configparser
import click
import requests
import controller as ctrl
from logbook import *
from config.base_settings import CAPTCHA_MODEL_NAME, TIMEOUT, USE_PROXY
from controller.url_config import url_captcha, url_login
from service.proxy import update_proxy, notify_ip_address, update_cookies
from service.sipoknn import get_captcha_result

        ctrl.BEING_LOG = False
        return True

    error_times = 0
    while True:
        try:
            # logger.debug("before proxy")
            update_proxy()
            # logger.debug("before cookie")
            update_cookies()
            # logger.debug("after cookie")
            busername = change_to_base64(username)
            bpassword = change_to_base64(password)
            captcha = get_captcha()
            logger.info('验证码识别结果：%s' % captcha)
            form_data = url_login.get('form_data')
            form_data.__setitem__('j_validation_code', captcha)
            form_data.__setitem__('j_username', busername)
            form_data.__setitem__('j_password', bpassword)

            resp = requests.post(url=url_login.get('url'), headers=url_login.get('headers'), data=form_data,
                                 cookies=ctrl.COOKIES, proxies=ctrl.PROXIES, timeout=TIMEOUT)
            if resp.text.find(username + '，欢迎访问') != -1:
                # 网站调整了逻辑，下面这句不用了
                # print(resp.cookies)
                # ctrl.COOKIES.__delitem__('IS_LOGIN')
                # ctrl.COOKIES.set('IS_LOGIN', 'true', domain='www.pss-system.gov.cn/sipopublicsearch/patentsearch')
                jsession = ctrl.COOKIES.get('JSESSIONID')
                resp.cookies.__delitem__('JSESSIONID')
                resp.cookies.set('JSESSIONID', jsession, domain='www.pss-system.gov.cn')

                update_cookies(resp.cookies)