Skip to content

Commit

Permalink
codeforces open/reg, fix contest list, move adaptor code to new folder
Browse files Browse the repository at this point in the history
  • Loading branch information
CroMarmot committed Sep 18, 2023
1 parent a3b16fd commit a505783
Show file tree
Hide file tree
Showing 15 changed files with 83 additions and 16 deletions.
2 changes: 1 addition & 1 deletion oi_cli2/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "0.2.2.5"
__version__ = "0.2.2.6"
3 changes: 3 additions & 0 deletions oi_cli2/cli/adaptor/AtCoderAdaptor.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,9 @@ def print_contest_list(self) -> bool:
printData(result)
return True

def cid2url(self, cid: str) -> str:
return f'{self._base_url}contests/{cid}'


def AtcoderGen(account: Account, provider: Provider2) -> BaseOj:
http_util = provider.get(DI_HTTP)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,8 @@ def reg_contest(self, contest_id: str) -> bool:
return self.async_2_sync_session_wrap(lambda: self.async_reg_contest(contest_id))

async def async_reg_contest(self, contest_id: str) -> bool:

if not await self.async_login_website():
raise Exception('Login Failed')
result = await async_register(http=self.http, contest_id=contest_id)
return result.msg == RegisterResultMsg.AlreadyRegistered or result.msg == RegisterResultMsg.HaveBeenRegistered

Expand Down Expand Up @@ -179,7 +180,7 @@ def page_result_transform(res: SubmissionPageResult) -> SubmissionResult:
self.logger.error('NOT HANDLE PAGE:' + str(res.verdict))

if res.url.startswith('/'):
res.url = 'https://codeforces.com' + res.url
res.url = self._base_url[:-1] + res.url

return SubmissionResult(id=res.id,
cur_status=cur_status,
Expand Down Expand Up @@ -209,7 +210,7 @@ def ws_result_transform(res: SubmissionWSResult) -> SubmissionResult:
cur_status=cur_status,
time_note=str(res.ms) + ' ms',
mem_note=str(int(res.mem) / 1000) + ' kb',
url=f'https://codeforces.com/contest/{res.contest_id}/submission/{res.submit_id}',
url=f'{self._base_url}contest/{res.contest_id}/submission/{res.submit_id}',
msg_txt=msg_txt,
)

Expand Down Expand Up @@ -320,3 +321,6 @@ async def async_print_friends_standing(self, cid: str) -> None:
result = await async_friends_standing(http=self.http, contest_id=cid)
from .standing import printData
printData(result, title=f"Friends standing {result.url}", handle=self.account.account)

def cid2url(self, cid: str) -> str:
return f'{self._base_url}contests/{cid}'
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@


def CodeforcesGen(account: Account, provider: Provider2) -> BaseOj:
from oi_cli2.custom.Codeforces.Codeforces import Codeforces
from oi_cli2.cli.adaptor.Codeforces.Codeforces import Codeforces
from codeforces_core.httphelper import HttpHelper
config_folder: ConfigFolder = provider.get(DI_CFG)
cookie_jar_path = config_folder.get_config_file_path(account.platform + '_' + account.account + '_cookies')
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,18 @@ def printData(cl: ContestList):
table.add_column("Start")
table.add_column("Length")
table.add_column("Before Start")
table.add_column("Reg")
table.add_column("Registered")
table.add_column("Id", style="magenta")

for item in cur:
startTime = datetime.fromtimestamp(item.start)
timediff = startTime - datetime.now()
if not item.participants: # 未开放注册
bgcolor = None
elif item.registered: # 已注册
bgcolor = 'dark_green'
else: # 开放注册,未注册
bgcolor = 'grey30'
table.add_row(
item.title,
# item["writers"], # tds[1].get_text().strip(),
Expand All @@ -37,8 +43,7 @@ def printData(cl: ContestList):
str(timedelta(days=timediff.days, seconds=timediff.seconds)) if timediff.days >= 0 else 'Started',
item.participants, # tds[5].get_text().strip(),
str(item.id), # tds[5].get_text().strip(),
style=Style(bgcolor=None if item.participants.startswith("Before") else (
"dark_green" if item.participants.startswith("Registered") else "grey30")))
style=Style(bgcolor=bgcolor))

console.print(table)

Expand Down
File renamed without changes.
2 changes: 2 additions & 0 deletions oi_cli2/cli/completion.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ def platformKey() -> Dict[str, Any]:
"detail": platformKey(),
"standing": platformKey(),
"fetch": platformKey(),
"open": platformKey(),
"reg": platformKey(),
},
"lang": platformKey(),
"test": {},
Expand Down
50 changes: 50 additions & 0 deletions oi_cli2/cli/contest.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import json
import logging
import os
import subprocess
import sys
import threading
import time
from requests.exceptions import ReadTimeout, ConnectTimeout
Expand Down Expand Up @@ -333,3 +335,51 @@ def standing(platform, contestid) -> None:
raise e

oj.print_friends_standing(cid=contestid)


@contest.command()
@click.argument('platform')
@click.argument('contestid')
def open(platform, contestid) -> None:

def open_url_with_default_browser(url: str) -> None:
if sys.platform == 'win32':
os.startfile(url)
elif sys.platform == 'darwin':
subprocess.Popen(['open', url])
else:
try:
subprocess.Popen(['xdg-open', url])
except OSError:
print("Please open a browser on: " + url)

logger: logging.Logger = Provider2().get(DI_LOGGER)
am: AccountManager = Provider2().get(DI_ACCMAN)

try:
oj: BaseOj = OJManager.createOj(platform=platform,
account=am.get_default_account(platform=platform),
provider=Provider2())
except Exception as e:
logger.exception(e)
raise e

open_url_with_default_browser(oj.cid2url(contestid))


@contest.command()
@click.argument('platform')
@click.argument('contestid')
def reg(platform, contestid) -> None:
logger: logging.Logger = Provider2().get(DI_LOGGER)
am: AccountManager = Provider2().get(DI_ACCMAN)

try:
oj: BaseOj = OJManager.createOj(platform=platform,
account=am.get_default_account(platform=platform),
provider=Provider2())
except Exception as e:
logger.exception(e)
raise e

oj.reg_contest(contestid)
8 changes: 4 additions & 4 deletions oi_cli2/cli/reg_list.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
from typing import Callable, Dict, List, Tuple, Union
from typing import Callable, Dict
from oi_cli2.cli.adaptor.AtCoderAdaptor import AtCoder, AtcoderGen
from oi_cli2.cli.adaptor.CodeforcesAdaptor import CodeforcesGen
from oi_cli2.custom.Codeforces.Codeforces import Codeforces
from oi_cli2.cli.adaptor.Codeforces.CodeforcesAdaptor import CodeforcesGen
from oi_cli2.cli.adaptor.Codeforces.Codeforces import Codeforces
from oi_cli2.model.Account import Account
from oi_cli2.model.BaseOj import BaseOj
from oi_cli2.utils.Provider2 import Provider2

reg_list: Dict[str, Callable[[Account, Provider2], BaseOj]] = {
Codeforces.__name__: CodeforcesGen,
AtCoder.__name__: AtcoderGen,
}
}
Empty file removed oi_cli2/custom/__init__.py
Empty file.
3 changes: 3 additions & 0 deletions oi_cli2/model/BaseOj.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,6 @@ def account_required() -> bool:
@staticmethod
def support_contest():
assert (False)

def cid2url(self, cid: str) -> str:
assert (False)
2 changes: 1 addition & 1 deletion oi_cli2/utils/OJUtil.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ class OJUtil(object):
def __init__(self):
self.short2class = {}

from oi_cli2.custom.Codeforces.Codeforces import Codeforces
from oi_cli2.cli.adaptor.Codeforces import Codeforces
self.reg(Codeforces)
# TODO atcoder

Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ dependencies = [
"click >= 8.1.3",
"rich >= 11.0.0",
"yxr-atcoder-core == 0.0.3.4",
"yxr-codeforces-core == 0.0.2.2",
"yxr-codeforces-core == 0.0.2.3",
]
readme = "README.md"
requires-python = ">=3.8"
Expand Down
4 changes: 2 additions & 2 deletions tests/custom/test_codeforces.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from oi_cli2.model.ParseProblemResult import ParsedProblemResult
from oi_cli2.model.TestCase import TestCase
from oi_cli2.model.BaseOj import BaseOj
from oi_cli2.custom.Codeforces.Codeforces import Codeforces
from oi_cli2.cli.adaptor.Codeforces.Codeforces import Codeforces
from oi_cli2.model.Account import Account

host = 'https://codeforces.com'
Expand All @@ -30,4 +30,4 @@ def test_problem_by_id():
assert result.mem_limit == '512 MB'
assert result.url == 'https://codeforces.com/contest/1843/problem/F2'
assert len(result.html) == 47603
assert result.file_path == '1843/F2'
assert result.file_path == '1843/F2'

0 comments on commit a505783

Please sign in to comment.