Exemplo n.º 1
0
    def submit(self, n):
        if not self.py_path.is_file():
            raise LeezyError(f'File not found: {self.py_path}')
        extractor = SolutionExtractor(self.py_path.read_text(encoding='utf8'))
        func, code = extractor.submission(n)
        # if there are multiple solutions,
        # we need to change function name before submitting
        if len(extractor) > 1:
            if self.content is None:
                self._lazy_init()
            origin_func_name = _find_func_names(self.code_snippet)[0]
            code = code.replace(func+'(', origin_func_name+'(')

        prelude = f"Is it OK to submit solution {func!r}?:\n{code}\n"
        if not YesNoDialog(prelude).collect():
            return

        payload = {
            "question_id": str(self.basic_info.question_id),
            "lang": "python3",
            "typed_code": code,
            "test_mode": False,
            "test_judger": "",
            "questionSlug": self.basic_info.title_slug
        }

        net = self.provider.net
        headers = {"referer": Urls.problem_home(self.basic_info.title_slug)}
        r = net.post(Urls.problem_submit(self.basic_info.title_slug),
                     purpose="submit a solution",
                     json=payload,
                     headers=headers)
        submission_id = r.json()['submission_id']
        check_url = Urls.submission_check(submission_id)

        check_cnt = 0
        r = None
        while True:
            time.sleep(1)
            r = net.get(check_url, purpose=f'check submission x {check_cnt}')
            if len(r.json()) > 1:
                break

        rjson = r.json()
        if 'status_code' in rjson:
            # append more infomation
            rjson.update({
                'discuss_url': Urls.problem_discussion(self.basic_info.title_slug),
                'submission_detail': Urls.submission_detail(submission_id),
            })
            SubmissionReporter(rjson).report()
        else:
            raise LeezyError(f'Bad submission: {r.text}')
Exemplo n.º 2
0
 def __init__(self):
     self.sess = requests.Session()
     self.sess.headers.update({
         'origin': Urls.portal(),
         'user-agent': ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
                        'AppleWebKit/537.36 (KHTML, like Gecko) '
                        'Chrome/80.0.3987.132 Safari/537.36')
     })
     # init csrf once using last local storage
     # `session` will hanlde the upating of csrf caused by multiple requests
     if not session_token.get_csrf():
         # update csrftoken
         Debug('Try initialize csrf')
         r = self.sess.post(Urls.graphql(),
                            json=UserStatusPayload().as_dict())
         found = session_token.try_update_csrf(r)
         if not found:
             Warn('Failed to intialize csrf')
     self.sess.cookies.update(session_token.get_csrf())
Exemplo n.º 3
0
    def __init__(self):
        self.net = Net()
        self.raw = self.net.get(Urls.api_problems_algo()).json()
        self.metadata = SimpleNamespace(
            **{
                'user_name': self.raw['user_name'],
                'num_solved': self.raw['num_solved'],
                'ac_easy': self.raw['ac_easy'],
                'ac_medium': self.raw['ac_medium'],
                'ac_hard': self.raw['ac_hard'],
            })

        ac = [None] * MAX_NUM
        attempt = [None] * MAX_NUM
        locked = [None] * MAX_NUM
        for stat in self.raw['stat_status_pairs']:
            try:
                front_id = int(stat['stat']['frontend_question_id'])
            except ValueError:
                continue
            if front_id > MAX_NUM:
                pass
            ac[front_id] = stat['status'] == 'ac'
            locked[front_id] = stat['paid_only']
            attempt[front_id] = stat['status'] == 'notac'

        max_id = MAX_NUM - 1
        while ac[max_id] is None:
            max_id -= 1
        max_id += 1
        ac = ac[:max_id]
        attempt = attempt[:max_id]
        locked = locked[:max_id]

        def none2false(arr):
            for i, x in enumerate(arr):
                if x is None:
                    arr[i] = False
            return arr

        self.max_id = max_id
        self.ac = none2false(ac)
        self.attempt = none2false(attempt)
        self.locked = none2false(locked)
Exemplo n.º 4
0
    def _cn_login_by_secret(self, username, password):
        Debug(f"Try to sign in {Urls.portal()} as {username!r}")
        # leetcode-cn.com
        payload = (LoginPayload().set_secret(username, password).as_dict())
        r = self.net._post(Urls.graphql(),
                           purpose="try to sign in LeetCode",
                           json=payload)

        if not r.json()['data']['authSignInWithPassword']['ok']:
            raise LoginError("Wrong username or password?")
        token = expires = None
        for c in r.cookies:
            if c.name == 'LEETCODE_SESSION':
                token = c.value
                expires = c.expires
                break
        else:
            raise LoginError("login successfully, "
                             "but didn't find session token in the response")
        return (token, expires)
Exemplo n.º 5
0
 def _raw_problem_detail(self, title_slug):
     payload = ProblemQueryPayload().set_title_slug(title_slug).as_dict()
     purpose = f"fetch problem {title_slug!r} detail"
     post = self.entry_repo.net.post
     r = post(Urls.graphql(), purpose=purpose, json=payload)
     return r.json()
Exemplo n.º 6
0
 def _raw_web_all_problems(self):
     purpose = "fetch the list of problem entry"
     r = self.net.get(Urls.api_problems_all(), purpose=purpose)
     return r.json()
Exemplo n.º 7
0
args = parser.parse_args()
if not hasattr(args, 'func'):
    parser.print_help()
else:
    if args.zone is not None:
        config.patch('core.zone', args.zone)
    if args.v is not None:
        if args.v == 1:
            config.patch('log.level', 'info')
        else:
            config.patch('log.level', 'debug')
    if args.dir is not None:
        config.patch('core.workdir', args.dir)

    session_token.init()
    Urls.init(config)

    log_lv = getattr(logging, config.get('log.level').upper())

    def reject_modules(modules, lv=logging.INFO):
        def _reject_filter(record):
            mod_name = record.name
            mod_lv = record.levelno
            for mod in modules:
                if mod_name.startswith(mod) and mod_lv <= lv:
                    return False
            return True

        return _reject_filter

    logging.basicConfig(level=log_lv)