orangehack 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,253 @@
1
+ """`attempts`, `status` and the wait of `submit --wait`: the scoring journal of a deliverable."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from typing import Annotated, Any
7
+
8
+ import typer
9
+
10
+ from .. import resolve
11
+ from ..errors import CliError, Exit
12
+ from ..output import table
13
+ from ..session import JsonOpt, Session, execute
14
+ from .competitions import case_keys, overview_of, when
15
+
16
+ STATES = {
17
+ "queued": "в очереди",
18
+ "running": "считается",
19
+ "checking": "проверяется",
20
+ "scored": "оценена",
21
+ "failed": "ошибка в решении",
22
+ "platform_error": "сбой платформы",
23
+ "refused": "отклонена",
24
+ "disqualified": "дисквалифицирована",
25
+ }
26
+ DONE = {"scored", "failed", "platform_error", "refused", "disqualified"}
27
+
28
+
29
+ def journal(s: Session, deliverable_id: str) -> dict[str, Any] | None:
30
+ """The scoring journal of a deliverable in `attempts` mode; None when there is none."""
31
+ try:
32
+ data: dict[str, Any] = s.client.get(
33
+ f"/api/v1/scoring/deliverables/{deliverable_id}/attempts"
34
+ )
35
+ except CliError as error:
36
+ if error.code in ("not_found", "http_404") or error.code.endswith("not_found"):
37
+ return None
38
+ raise
39
+ return data
40
+
41
+
42
+ def attempt_of(s: Session, deliverable_id: str, submission_id: str) -> dict[str, Any] | None:
43
+ try:
44
+ found = journal(s, deliverable_id)
45
+ except CliError:
46
+ return None
47
+ for attempt in (found or {}).get("attempts", []):
48
+ if str(attempt.get("submission_id")) == submission_id:
49
+ return dict(attempt)
50
+ return None
51
+
52
+
53
+ def own_place(s: Session, competition_id: str, deliverable_id: str) -> list[dict[str, Any]]:
54
+ try:
55
+ rows = s.client.get(
56
+ f"/api/v1/leaderboard/competitions/{competition_id}/own",
57
+ params={"deliverable": deliverable_id},
58
+ )
59
+ except CliError:
60
+ return []
61
+ return list(rows or [])
62
+
63
+
64
+ def _value(attempt: dict[str, Any]) -> str:
65
+ value = attempt.get("value")
66
+ return "—" if value is None else f"{value:g}" if isinstance(value, float) else str(value)
67
+
68
+
69
+ def wait_for_score(
70
+ s: Session,
71
+ competition: resolve.Competition,
72
+ deliverable: resolve.Deliverable,
73
+ submission_id: str,
74
+ timeout: int,
75
+ ) -> dict[str, Any]:
76
+ if not deliverable.scored:
77
+ s.output.say("Эта сдача не оценивается автоматически: оценку поставят организаторы.")
78
+ return {"state": "not_scored"}
79
+ started = time.monotonic()
80
+ delay = 2.0
81
+ attempt: dict[str, Any] | None = None
82
+ while True:
83
+ attempt = attempt_of(s, deliverable.id, submission_id)
84
+ state = (attempt or {}).get("state", "checking")
85
+ s.output.progress(f"Оценка: {STATES.get(state, state)}…")
86
+ if state in DONE:
87
+ break
88
+ if s.options.sleep is None and time.monotonic() - started > timeout:
89
+ s.output.progress_done()
90
+ raise CliError(
91
+ Exit.NETWORK,
92
+ "Оценка ещё не готова.",
93
+ f"Проверьте позже: orangehack status {competition.address} {submission_id}",
94
+ code="wait_timeout",
95
+ )
96
+ s.sleep(delay)
97
+ delay = min(delay * 1.5, 15.0)
98
+ s.output.progress_done()
99
+ assert attempt is not None
100
+ if state != "scored":
101
+ reason = attempt.get("message") or STATES.get(state, state)
102
+ raise CliError(
103
+ Exit.REFUSED,
104
+ f"Попытка не оценена: {reason}",
105
+ code=state,
106
+ extra={"attempt": attempt},
107
+ )
108
+ places = own_place(s, competition.id, deliverable.id)
109
+ s.output.say(f"Оценка: {_value(attempt)}")
110
+ for place in places:
111
+ if place.get("hidden"):
112
+ s.output.say(f"Место ({place.get('case_title')}): таблица закрыта для участников.")
113
+ elif place.get("rank"):
114
+ s.output.say(f"Место ({place.get('case_title')}): {place['rank']} из {place.get('of')}")
115
+ return {"state": state, "attempt": attempt, "places": places}
116
+
117
+
118
+ def _scored(
119
+ s: Session, competition: str, case: str | None, deliverable: str | None
120
+ ) -> tuple[resolve.Competition, list[resolve.Deliverable]]:
121
+ target = resolve.competition(s.signed_in(), competition)
122
+ overview = overview_of(s, target)
123
+ items = resolve.narrow(
124
+ resolve.deliverables(overview),
125
+ case=case,
126
+ deliverable=deliverable,
127
+ case_keys=case_keys(s, target) if case else None,
128
+ )
129
+ return target, items
130
+
131
+
132
+ def attempts(
133
+ ctx: typer.Context,
134
+ competition: Annotated[str, typer.Argument(help="Адрес (организация/соревнование) или id.")],
135
+ case: Annotated[str | None, typer.Option("--case", help="Ключ или название кейса.")] = None,
136
+ deliverable: Annotated[
137
+ str | None, typer.Option("--deliverable", "-d", help="Ключ или название сдачи.")
138
+ ] = None,
139
+ json_: JsonOpt = False,
140
+ ) -> None:
141
+ """Мои попытки и оценки, с лимитом на сегодня."""
142
+
143
+ def body(s: Session) -> None:
144
+ target, items = _scored(s, competition, case, deliverable)
145
+ result = []
146
+ for d in items:
147
+ found = journal(s, d.id) if d.scored else None
148
+ if found is not None:
149
+ result.append({"deliverable": d.key, "title": d.title, "scored": True, **found})
150
+ continue
151
+ detail = s.client.get(
152
+ f"/api/v1/deliverables/competitions/{target.id}/deliverables/{d.id}"
153
+ )
154
+ result.append(
155
+ {
156
+ "deliverable": d.key,
157
+ "title": d.title,
158
+ "scored": False,
159
+ "versions": detail.get("versions", []),
160
+ }
161
+ )
162
+
163
+ def human() -> None:
164
+ for entry in result:
165
+ s.output.say(f"{entry['title']} ({entry['deliverable']})")
166
+ if entry["scored"]:
167
+ standing = entry.get("standing") or {}
168
+ rows = [
169
+ [
170
+ a.get("uid") or a.get("version"),
171
+ when(a.get("submitted_at")),
172
+ STATES.get(a.get("state", ""), a.get("state", "")),
173
+ _value(a),
174
+ (a.get("message") or a.get("name") or "")[:60],
175
+ ]
176
+ for a in entry.get("attempts", [])
177
+ ]
178
+ s.output.say(
179
+ table(["Попытка", "Когда", "Статус", "Оценка", "Заметка"], rows)
180
+ if rows
181
+ else " попыток нет"
182
+ )
183
+ if standing.get("limit") is not None:
184
+ s.output.say(
185
+ f" Сегодня: {standing.get('used', 0)} из {standing['limit']}, "
186
+ f"новые попытки с {when(standing.get('resets_at'))}"
187
+ )
188
+ else:
189
+ rows = [
190
+ [
191
+ v.get("version"),
192
+ when(v.get("submitted_at")),
193
+ "принята"
194
+ if v.get("status") == "accepted"
195
+ else (v.get("refusal") or {}).get("message", "отклонена"),
196
+ (v.get("payload") or {}).get("filename")
197
+ or (v.get("payload") or {}).get("url")
198
+ or "",
199
+ ]
200
+ for v in entry.get("versions", [])
201
+ ]
202
+ s.output.say(
203
+ table(["Версия", "Когда", "Статус", "Что"], rows)
204
+ if rows
205
+ else " версий нет"
206
+ )
207
+ s.output.say("")
208
+
209
+ s.output.result({"competition": target.__dict__, "deliverables": result}, human)
210
+
211
+ execute(ctx, json_, body)
212
+
213
+
214
+ def status(
215
+ ctx: typer.Context,
216
+ competition: Annotated[str, typer.Argument(help="Адрес (организация/соревнование) или id.")],
217
+ attempt: Annotated[str, typer.Argument(help="Номер попытки (uid) или id версии.")],
218
+ json_: JsonOpt = False,
219
+ ) -> None:
220
+ """Состояние одной попытки."""
221
+
222
+ def body(s: Session) -> None:
223
+ _, items = _scored(s, competition, None, None)
224
+ needle = attempt.strip().casefold()
225
+ for d in items:
226
+ if not d.scored:
227
+ continue
228
+ found = journal(s, d.id) or {}
229
+ for a in found.get("attempts", []):
230
+ if needle in (
231
+ str(a.get("uid", "")).casefold(),
232
+ str(a.get("submission_id", "")).casefold(),
233
+ ):
234
+
235
+ def human(a: dict[str, Any] = a, d: resolve.Deliverable = d) -> None:
236
+ s.output.say(f"{d.title}: попытка {a.get('uid') or a.get('version')}")
237
+ s.output.say(f"Статус: {STATES.get(a.get('state', ''), a.get('state'))}")
238
+ s.output.say(f"Оценка: {_value(a)}")
239
+ if a.get("message"):
240
+ s.output.say(f"Сообщение: {a['message']}")
241
+
242
+ s.output.result({"deliverable": d.key, "attempt": a}, human)
243
+ if a.get("state") in ("failed", "platform_error", "refused", "disqualified"):
244
+ # The result is printed; the exit code still says the run failed.
245
+ raise typer.Exit(int(Exit.REFUSED))
246
+ return
247
+ raise CliError(
248
+ Exit.USAGE,
249
+ f"Попытка «{attempt}» не найдена.",
250
+ "Список: orangehack attempts <соревнование>",
251
+ )
252
+
253
+ execute(ctx, json_, body)
@@ -0,0 +1,224 @@
1
+ """`login`, `logout`, `whoami`: the device-code sign-in of `api-tokens`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import socket
7
+ import time
8
+ import webbrowser
9
+ from typing import Annotated, Any
10
+ from urllib.parse import urlsplit
11
+
12
+ import typer
13
+
14
+ from .. import config
15
+ from ..errors import ApiError, CliError, Exit, from_api
16
+ from ..output import table
17
+ from ..session import JsonOpt, Session, execute
18
+
19
+ DEFAULT_SCOPES = "read,submit"
20
+
21
+
22
+ def _client_name(name: str | None) -> str:
23
+ if name:
24
+ return name[:60]
25
+ host = socket.gethostname().split(".")[0] or "терминал"
26
+ return f"orangehack-cli · {host}"[:60]
27
+
28
+
29
+ def _same_site(address: str, base: str) -> bool:
30
+ """An http(s) address on the platform's own host."""
31
+ target, platform = urlsplit(str(address)), urlsplit(base)
32
+ return target.scheme in ("http", "https") and target.hostname == platform.hostname
33
+
34
+
35
+ def _start(s: Session, client_name: str, scopes: list[str]) -> dict[str, Any]:
36
+ response = s.client.send(
37
+ "POST",
38
+ "/api/v1/accounts/tokens/device",
39
+ auth=False,
40
+ json={"client_name": client_name, "scopes": scopes},
41
+ )
42
+ data: dict[str, Any] = response.json()
43
+ return data
44
+
45
+
46
+ def login(
47
+ ctx: typer.Context,
48
+ scope: Annotated[
49
+ str, typer.Option("--scope", help="Права токена через запятую: read, submit.")
50
+ ] = DEFAULT_SCOPES,
51
+ name: Annotated[
52
+ str | None, typer.Option("--name", help="Как токен назовётся в «Доступ по API».")
53
+ ] = None,
54
+ no_browser: Annotated[
55
+ bool, typer.Option("--no-browser", help="Не открывать браузер, только показать адрес.")
56
+ ] = False,
57
+ json_: JsonOpt = False,
58
+ ) -> None:
59
+ """Войти: подтвердить код в браузере и сохранить токен на этом компьютере."""
60
+
61
+ def body(s: Session) -> None:
62
+ if s.profile.source == "env":
63
+ s.output.note("ORANGEHACK_TOKEN задан: команды используют его, вход не нужен.")
64
+ scopes = [part.strip() for part in scope.split(",") if part.strip()]
65
+ client_name = _client_name(name)
66
+ try:
67
+ try:
68
+ started = _start(s, client_name, scopes)
69
+ except ApiError as error:
70
+ if error.code != "token_scope_unavailable" or scope != DEFAULT_SCOPES:
71
+ raise
72
+ # The platform has not switched hand-ins by token on yet: sign in to read.
73
+ s.output.note(
74
+ "Сдача из терминала на платформе пока выключена — вход только на чтение."
75
+ )
76
+ scopes = ["read"]
77
+ started = _start(s, client_name, scopes)
78
+ except ApiError as error:
79
+ raise from_api(error, base_url=s.profile.url) from error
80
+ code = started["user_code"]
81
+ address = started.get("verification_uri_complete") or started["verification_uri"]
82
+ s.output.note(f"Код: {code}")
83
+ s.output.note(f"Подтвердите вход в браузере: {address}")
84
+ s.output.note("Разрешайте, только если код совпадает с этим.")
85
+ own = _same_site(address, s.profile.url)
86
+ if not own:
87
+ # The address came from the answer: the browser opens only the platform's own pages.
88
+ s.output.note(
89
+ f"Этот адрес не на {s.profile.url}: открывайте его, только если доверяете ему."
90
+ )
91
+ if own and not no_browser:
92
+ opener = s.options.open_browser or webbrowser.open
93
+ # No browser here (a server, a container): the address is printed above.
94
+ with contextlib.suppress(Exception):
95
+ opener(address)
96
+ interval = float(started.get("interval") or 5)
97
+ deadline = time.monotonic() + float(started.get("expires_in") or 600)
98
+ token: dict[str, Any] | None = None
99
+ while token is None:
100
+ s.sleep(interval)
101
+ try:
102
+ token = s.client.send(
103
+ "POST",
104
+ "/api/v1/accounts/tokens/device/token",
105
+ auth=False,
106
+ json={"device_code": started["device_code"]},
107
+ ).json()
108
+ except ApiError as error:
109
+ if error.code == "authorization_pending":
110
+ if s.options.sleep is None and time.monotonic() > deadline:
111
+ raise CliError(
112
+ Exit.SIGNED_OUT,
113
+ "Код истёк, вход не подтверждён.",
114
+ "Запустите orangehack login ещё раз.",
115
+ code="expired_token",
116
+ ) from error
117
+ continue
118
+ if error.code == "slow_down":
119
+ interval += 5
120
+ continue
121
+ if error.code == "access_denied":
122
+ raise CliError(
123
+ Exit.SIGNED_OUT,
124
+ "Вход отклонён в браузере.",
125
+ "Если это были вы, запустите orangehack login ещё раз.",
126
+ code="access_denied",
127
+ ) from error
128
+ if error.code == "expired_token":
129
+ raise CliError(
130
+ Exit.SIGNED_OUT,
131
+ "Код истёк, вход не подтверждён.",
132
+ "Запустите orangehack login ещё раз.",
133
+ code="expired_token",
134
+ ) from error
135
+ raise from_api(error, base_url=s.profile.url) from error
136
+ assert token is not None
137
+ s.profile.token_id = str(token.get("token_id", ""))
138
+ s.profile.scopes = list(token.get("scopes") or scopes)
139
+ where = config.save(s.profile, str(token["token"]))
140
+ s.profile.token = str(token["token"])
141
+ s.client.token = s.profile.token
142
+ me = s.client.get("/api/v1/accounts/tokens/current")
143
+ stored = "в системном хранилище ключей" if where == "keyring" else f"в файле {where}"
144
+
145
+ def human() -> None:
146
+ s.output.say(f"Вы вошли как {_who(me)}. Токен сохранён {stored}.")
147
+ s.output.say(
148
+ f"Права: {', '.join(s.profile.scopes)}; действует до {_date(token.get('expires_at'))}."
149
+ )
150
+
151
+ s.output.result(
152
+ {"profile": s.profile.name, "url": s.profile.url, "user": _public(me), "stored": where},
153
+ human,
154
+ )
155
+
156
+ execute(ctx, json_, body)
157
+
158
+
159
+ def logout(ctx: typer.Context, json_: JsonOpt = False) -> None:
160
+ """Забыть токен на этом компьютере. Отозвать его совсем — на сайте, «Доступ по API»."""
161
+
162
+ def body(s: Session) -> None:
163
+ had = config.forget(s.profile)
164
+ revoke = f"{s.profile.url}/accounts/api"
165
+
166
+ def human() -> None:
167
+ s.output.say("Токен удалён с этого компьютера." if had else "Сохранённого токена нет.")
168
+ s.output.say(f"Чтобы токен перестал действовать везде, отзовите его: {revoke}")
169
+ if s.profile.source == "env":
170
+ s.output.say("ORANGEHACK_TOKEN в окружении по-прежнему задан.")
171
+
172
+ s.output.result({"forgotten": had, "revoke_at": revoke}, human)
173
+
174
+ execute(ctx, json_, body)
175
+
176
+
177
+ def _who(me: dict[str, Any]) -> str:
178
+ nickname = me.get("nickname") or me.get("display_name") or "—"
179
+ return f"{nickname} (UID {me.get('uid', '—')})"
180
+
181
+
182
+ def _date(value: Any) -> str:
183
+ return str(value or "—").replace("T", " ")[:16]
184
+
185
+
186
+ def _public(me: dict[str, Any]) -> dict[str, Any]:
187
+ token = me.get("token") or {}
188
+ return {
189
+ "uid": me.get("uid"),
190
+ "nickname": me.get("nickname"),
191
+ "display_name": me.get("display_name"),
192
+ "token": {k: token.get(k) for k in ("id", "name", "scopes", "expires_at")},
193
+ }
194
+
195
+
196
+ def whoami(ctx: typer.Context, json_: JsonOpt = False) -> None:
197
+ """Кто вошёл: ник, UID, название токена, его права и срок. Сам токен не показывается."""
198
+
199
+ def body(s: Session) -> None:
200
+ me = s.signed_in().get("/api/v1/accounts/tokens/current")
201
+ token = me.get("token") or {}
202
+
203
+ def human() -> None:
204
+ s.output.say(
205
+ table(
206
+ ["", ""],
207
+ [
208
+ ["Ник", me.get("nickname") or "—"],
209
+ ["Имя", me.get("display_name") or "—"],
210
+ ["UID", me.get("uid") or "—"],
211
+ ["Токен", token.get("name") or "—"],
212
+ ["Права", ", ".join(token.get("scopes") or [])],
213
+ ["Действует до", _date(token.get("expires_at"))],
214
+ ["Платформа", s.profile.url],
215
+ ["Профиль", s.profile.name],
216
+ ],
217
+ ).split("\n", 1)[1]
218
+ )
219
+
220
+ s.output.result(
221
+ {"user": _public(me), "url": s.profile.url, "profile": s.profile.name}, human
222
+ )
223
+
224
+ execute(ctx, json_, body)