Skip to content

Commit

Permalink
Merge pull request #125 from online-judge-tools/fix/codeforces-ua
Browse files Browse the repository at this point in the history
Use action in FormSender to fix the issue on Codeforces
  • Loading branch information
kmyk authored Dec 14, 2020
2 parents e5f3a7f + 189a2c7 commit 8c410d4
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 10 deletions.
2 changes: 2 additions & 0 deletions onlinejudge/_implementation/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,8 @@ def request(self, session: requests.Session, method: str = None, action: Optiona
if method is None:
method = self.form['method'].upper()
url = self.url
if action is None and 'action' in self.form.attrs:
action = self.form.attrs['action']
if action is not None:
url = urllib.parse.urljoin(self.url, action)
if headers is None:
Expand Down
26 changes: 16 additions & 10 deletions onlinejudge/service/codeforces.py
Original file line number Diff line number Diff line change
Expand Up @@ -362,37 +362,43 @@ def submit_code(self, code: bytes, language_id: LanguageId, *, filename: Optiona
"""

session = session or utils.get_default_session()

# get
resp = utils.request('GET', self.get_url(), session=session)
url = self.get_contest().get_url() + '/submit'
resp = utils.request('GET', url, session=session)

# parse
soup = bs4.BeautifulSoup(resp.content.decode(resp.encoding), utils.HTML_PARSER)
form = soup.find('form', class_='submitForm')
form = soup.find('form', class_='submit-form')
if form is None:
logger.error('not logged in')
raise NotLoggedInError
logger.debug('form: %s', str(form))

# make data
form = utils.FormSender(form, url=resp.url)
form.set('submittedProblemIndex', str(self.index))
form.set('programTypeId', language_id)
form.set_file('sourceFile', filename or 'code', code)

# post
preserved_user_agent = session.headers.get('User-Agent')
logger.debug('User-Agent is temporarily disabled. The old User-Agent is %s', repr(preserved_user_agent))
try:
if preserved_user_agent is not None:
del session.headers['User-Agent']
resp = form.request(session=session, raise_for_status=False)
try:
resp.raise_for_status()
except requests.exceptions.HTTPError as e:
logger.exception(e)
if resp.status_code == 403:
logger.warning('You may use wrong User-Agent: %s', repr(session.headers.get('User-Agent')))
raise e
finally:
if preserved_user_agent is not None:
session.headers['User-Agent'] = preserved_user_agent
try:
resp.raise_for_status()
except requests.exceptions.HTTPError as e:
logger.exception(e)
if resp.status_code == 403:
logger.warning('You may use wrong User-Agent: %s', repr(session.headers.get('User-Agent')))
raise SubmissionError('You may use wrong User-Agent: {}: {}'.format(repr(session.headers.get('User-Agent')), e))
raise e

# result
if resp.url.endswith('/my'):
# example: https://codeforces.com/contest/598/my
Expand Down

0 comments on commit 8c410d4

Please sign in to comment.