Skip to content

Commit bbeb683

Browse files
cmyuiJoshpre-commit-ci[bot]
authored
More strict mypy config (#701)
* Improved mypy config * Ignore venv in mypy * More strict mypy config * incl * reorder * exit poetry package mode * some type error fixes * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * 0 type errors remain * name & unused imports * minor cleanups --------- Co-authored-by: Josh <joshua.smith@super.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 24f0ab1 commit bbeb683

File tree

13 files changed

+90
-91
lines changed

13 files changed

+90
-91
lines changed

app/api/domains/cho.py

Lines changed: 27 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44

55
import asyncio
66
import hashlib
7-
import logging
87
import re
98
import struct
109
import time
@@ -18,7 +17,6 @@
1817
from zoneinfo import ZoneInfo
1918

2019
import bcrypt
21-
import databases.core
2220
from fastapi import APIRouter
2321
from fastapi import Response
2422
from fastapi.param_functions import Header
@@ -298,7 +296,7 @@ async def handle(self, player: Player) -> None:
298296
app.state.sessions.players.enqueue(app.packets.user_stats(player))
299297

300298

301-
IGNORED_CHANNELS = ["#highlight", "#userlog"]
299+
IGNORED_CHANNELS: list[str] = ["#highlight", "#userlog"]
302300

303301

304302
@register(ClientPackets.SEND_PUBLIC_MESSAGE)
@@ -886,14 +884,14 @@ async def handle_osu_login_request(
886884
if (
887885
not channel.auto_join
888886
or not channel.can_read(player.priv)
889-
or channel._name == "#lobby" # (can't be in mp lobby @ login)
887+
or channel.real_name == "#lobby" # (can't be in mp lobby @ login)
890888
):
891889
continue
892890

893891
# send chan info to all players who can see
894892
# the channel (to update their playercounts)
895893
chan_info_packet = app.packets.channel_info(
896-
channel._name,
894+
channel.real_name,
897895
channel.topic,
898896
len(channel.players),
899897
)
@@ -950,29 +948,28 @@ async def handle_osu_login_request(
950948
read=False,
951949
)
952950

953-
if mail_rows:
954-
sent_to: set[int] = set()
955-
956-
for msg in mail_rows:
957-
# Add "Unread messages" header as the first message
958-
# for any given sender, to make it clear that the
959-
# messages are coming from the mail system.
960-
if msg["from_id"] not in sent_to:
961-
data += app.packets.send_message(
962-
sender=msg["from_name"],
963-
msg="Unread messages",
964-
recipient=msg["to_name"],
965-
sender_id=msg["from_id"],
966-
)
967-
sent_to.add(msg["from_id"])
951+
sent_to: set[int] = set()
968952

969-
msg_time = datetime.fromtimestamp(msg["time"])
953+
for msg in mail_rows:
954+
# Add "Unread messages" header as the first message
955+
# for any given sender, to make it clear that the
956+
# messages are coming from the mail system.
957+
if msg["from_id"] not in sent_to:
970958
data += app.packets.send_message(
971959
sender=msg["from_name"],
972-
msg=f'[{msg_time:%a %b %d @ %H:%M%p}] {msg["msg"]}',
960+
msg="Unread messages",
973961
recipient=msg["to_name"],
974962
sender_id=msg["from_id"],
975963
)
964+
sent_to.add(msg["from_id"])
965+
966+
msg_time = datetime.fromtimestamp(msg["time"])
967+
data += app.packets.send_message(
968+
sender=msg["from_name"],
969+
msg=f'[{msg_time:%a %b %d @ %H:%M%p}] {msg["msg"]}',
970+
recipient=msg["to_name"],
971+
sender_id=msg["from_id"],
972+
)
976973

977974
if not player.priv & Privileges.VERIFIED:
978975
# this is the player's first login, verify their
@@ -1025,10 +1022,10 @@ async def handle_osu_login_request(
10251022

10261023
if app.state.services.datadog:
10271024
if not player.restricted:
1028-
app.state.services.datadog.increment("bancho.online_players")
1025+
app.state.services.datadog.increment("bancho.online_players") # type: ignore[no-untyped-call]
10291026

10301027
time_taken = time.time() - login_time
1031-
app.state.services.datadog.histogram("bancho.login_time", time_taken)
1028+
app.state.services.datadog.histogram("bancho.login_time", time_taken) # type: ignore[no-untyped-call]
10321029

10331030
user_os = "unix (wine)" if running_under_wine else "win32"
10341031
country_code = player.geoloc["country"]["acronym"].upper()
@@ -1763,7 +1760,9 @@ async def handle(self, player: Player) -> None:
17631760

17641761
if player.match.is_scrimming:
17651762
# determine winner, update match points & inform players.
1766-
asyncio.create_task(player.match.update_matchpoints(was_playing))
1763+
asyncio.create_task( # type: ignore[unused-awaitable]
1764+
player.match.update_matchpoints(was_playing),
1765+
)
17671766

17681767

17691768
@register(ClientPackets.MATCH_CHANGE_MODS)
@@ -2109,7 +2108,9 @@ def __init__(self, reader: BanchoPacketReader) -> None:
21092108

21102109
async def handle(self, player: Player) -> None:
21112110
unrestrcted_ids = [p.id for p in app.state.sessions.players.unrestricted]
2112-
is_online = lambda o: o in unrestrcted_ids and o != player.id
2111+
2112+
def is_online(o: int) -> bool:
2113+
return o in unrestrcted_ids and o != player.id
21132114

21142115
for online in filter(is_online, self.user_ids):
21152116
target = app.state.sessions.players.get(id=online)

app/api/domains/osu.py

Lines changed: 9 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,7 @@ async def osuGetBeatmapInfo(
190190
num_requests = len(form_data.Filenames) + len(form_data.Ids)
191191
log(f"{player} requested info for {num_requests} maps.", Ansi.LCYAN)
192192

193-
ret = []
193+
response_lines: list[str] = []
194194

195195
for idx, map_filename in enumerate(form_data.Filenames):
196196
# try getting the map from sql
@@ -214,7 +214,7 @@ async def osuGetBeatmapInfo(
214214
):
215215
grades[score["mode"]] = score["grade"]
216216

217-
ret.append(
217+
response_lines.append(
218218
"{i}|{id}|{set_id}|{md5}|{status}|{grades}".format(
219219
i=idx,
220220
id=beatmap["id"],
@@ -230,7 +230,7 @@ async def osuGetBeatmapInfo(
230230
f"{player} requested map(s) info by id ({form_data.Ids})",
231231
)
232232

233-
return Response("\n".join(ret).encode())
233+
return Response("\n".join(response_lines).encode())
234234

235235

236236
@router.get("/web/osu-getfavourites.php")
@@ -707,11 +707,11 @@ async def osuSubmitModularSelector(
707707
""" Score submission checks completed; submit the score. """
708708

709709
if app.state.services.datadog:
710-
app.state.services.datadog.increment("bancho.submitted_scores")
710+
app.state.services.datadog.increment("bancho.submitted_scores") # type: ignore[no-untyped-call]
711711

712712
if score.status == SubmissionStatus.BEST:
713713
if app.state.services.datadog:
714-
app.state.services.datadog.increment("bancho.submitted_scores_best")
714+
app.state.services.datadog.increment("bancho.submitted_scores_best") # type: ignore[no-untyped-call]
715715

716716
if score.bmap.has_leaderboard:
717717
if score.bmap.status == RankedStatus.Loved and score.mode in (
@@ -1093,7 +1093,7 @@ async def getReplay(
10931093

10941094
# increment replay views for this score
10951095
if score.player is not None and player.id != score.player.id:
1096-
app.state.loop.create_task(score.increment_replay_views())
1096+
app.state.loop.create_task(score.increment_replay_views()) # type: ignore[unused-awaitable]
10971097

10981098
return FileResponse(file)
10991099

@@ -1302,6 +1302,7 @@ async def getScores(
13021302

13031303
map_filename = unquote_plus(map_filename) # TODO: is unquote needed?
13041304

1305+
map_exists = False
13051306
if has_set_id:
13061307
# we can look it up in the specific set from cache
13071308
for bmap in app.state.cache.beatmapset[map_set_id].maps:
@@ -1335,7 +1336,7 @@ async def getScores(
13351336
# we've found a beatmap for the request.
13361337

13371338
if app.state.services.datadog:
1338-
app.state.services.datadog.increment("bancho.leaderboards_served")
1339+
app.state.services.datadog.increment("bancho.leaderboards_served") # type: ignore[no-untyped-call]
13391340

13401341
if bmap.status < RankedStatus.Ranked:
13411342
# only show leaderboards for ranked,
@@ -1546,14 +1547,6 @@ async def banchoConnect(
15461547
return Response(b"")
15471548

15481549

1549-
_checkupdates_cache = { # default timeout is 1h, set on request.
1550-
"cuttingedge": {"check": None, "path": None, "timeout": 0},
1551-
"stable40": {"check": None, "path": None, "timeout": 0},
1552-
"beta40": {"check": None, "path": None, "timeout": 0},
1553-
"stable": {"check": None, "path": None, "timeout": 0},
1554-
}
1555-
1556-
15571550
@router.get("/web/check-updates.php")
15581551
async def checkUpdates(
15591552
request: Request,
@@ -1770,7 +1763,7 @@ async def register_account(
17701763
await stats_repo.create_all_modes(player_id=player["id"])
17711764

17721765
if app.state.services.datadog:
1773-
app.state.services.datadog.increment("bancho.registrations")
1766+
app.state.services.datadog.increment("bancho.registrations") # type: ignore[no-untyped-call]
17741767

17751768
log(f"<{username} ({player['id']})> has registered!", Ansi.LGREEN)
17761769

app/api/init_api.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -83,14 +83,14 @@ async def lifespan(asgi_app: BanchoAPI) -> AsyncIterator[None]:
8383
)
8484

8585
await app.state.services.database.connect()
86-
await app.state.services.redis.initialize()
86+
await app.state.services.redis.initialize() # type: ignore[unused-awaitable]
8787

8888
if app.state.services.datadog is not None:
89-
app.state.services.datadog.start(
89+
app.state.services.datadog.start( # type: ignore[no-untyped-call]
9090
flush_in_thread=True,
9191
flush_interval=15,
9292
)
93-
app.state.services.datadog.gauge("bancho.online_players", 0)
93+
app.state.services.datadog.gauge("bancho.online_players", 0) # type: ignore[no-untyped-call]
9494

9595
app.state.services.ip_resolver = app.state.services.IPResolver()
9696

@@ -119,8 +119,8 @@ async def lifespan(asgi_app: BanchoAPI) -> AsyncIterator[None]:
119119
await app.state.services.redis.aclose()
120120

121121
if app.state.services.datadog is not None:
122-
app.state.services.datadog.stop()
123-
app.state.services.datadog.flush()
122+
app.state.services.datadog.stop() # type: ignore[no-untyped-call]
123+
app.state.services.datadog.flush() # type: ignore[no-untyped-call]
124124

125125

126126
def init_exception_handlers(asgi_app: BanchoAPI) -> None:

app/api/v1/api.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@
6666

6767
@router.get("/calculate_pp")
6868
async def api_calculate_pp(
69-
token: HTTPCredentials = Depends(http_bearer_scheme),
69+
token: HTTPCredentials | None = Depends(http_bearer_scheme),
7070
beatmap_id: int = Query(None, alias="id", min=0, max=2_147_483_647),
7171
nkatu: int = Query(None, max=2_147_483_647),
7272
ngeki: int = Query(None, max=2_147_483_647),

app/commands.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -424,7 +424,10 @@ def parse__with__command_args(
424424
return ParsingError("Invalid syntax: !with <acc/nmiss/combo/mods ...>")
425425

426426
# !with 95% 1m 429x hddt
427-
acc = mods = combo = nmiss = None
427+
combo: int | None = None
428+
nmiss: int | None = None
429+
mods: Mods | None = None
430+
acc: float | None = None
428431

429432
# parse acc, misses, combo and mods from arguments.
430433
# tried to balance complexity vs correctness here
@@ -877,7 +880,7 @@ async def user(ctx: Context) -> str | None:
877880
f'[{"Bot" if player.is_bot_client else "Player"}] {display_name} ({player.id})',
878881
f"Privileges: {priv_list}",
879882
f"Donator: {donator_info}",
880-
f"Channels: {[c._name for c in player.channels]}",
883+
f"Channels: {[c.real_name for c in player.channels]}",
881884
f"Logged in: {timeago.format(player.login_time)}",
882885
f"Last server interaction: {timeago.format(player.last_recv_time)}",
883886
f"osu! build: {osu_version} | Tourney: {player.is_tourney_client}",
@@ -1639,7 +1642,7 @@ async def mp_addref(ctx: Context, match: Match) -> str | None:
16391642
if target in match.refs:
16401643
return f"{target} is already a match referee!"
16411644

1642-
match._refs.add(target)
1645+
match.referees.add(target)
16431646
return f"{target.name} added to match referees."
16441647

16451648

@@ -1660,7 +1663,7 @@ async def mp_rmref(ctx: Context, match: Match) -> str | None:
16601663
if target is match.host:
16611664
return "The host is always a referee!"
16621665

1663-
match._refs.remove(target)
1666+
match.referees.remove(target)
16641667
return f"{target.name} removed from match referees."
16651668

16661669

@@ -2487,6 +2490,7 @@ async def process_commands(
24872490
trigger = trigger.lower()
24882491

24892492
# check if any command sets match.
2493+
commands: list[Command] = []
24902494
for cmd_set in command_sets:
24912495
if trigger == cmd_set.trigger:
24922496
if not args:

app/objects/channel.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -37,15 +37,14 @@ def __init__(
3737
auto_join: bool = True,
3838
instance: bool = False,
3939
) -> None:
40-
# TODO: think of better names than `_name` and `name`
41-
self._name = name # 'real' name ('#{multi/spec}_{id}')
40+
self.real_name = name
4241

43-
if self._name.startswith("#spec_"):
42+
if self.real_name.startswith("#spec_"):
4443
self.name = "#spectator"
45-
elif self._name.startswith("#multi_"):
44+
elif self.real_name.startswith("#multi_"):
4645
self.name = "#multiplayer"
4746
else:
48-
self.name = self._name
47+
self.name = self.real_name
4948

5049
self.topic = topic
5150
self.read_priv = read_priv
@@ -56,7 +55,7 @@ def __init__(
5655
self.players: list[Player] = []
5756

5857
def __repr__(self) -> str:
59-
return f"<{self._name}>"
58+
return f"<{self.real_name}>"
6059

6160
def __contains__(self, player: Player) -> bool:
6261
return player in self.players

app/objects/collections.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,12 +41,12 @@ def __repr__(self) -> str:
4141
# XXX: we use the "real" name, aka
4242
# #multi_1 instead of #multiplayer
4343
# #spect_1 instead of #spectator.
44-
return f'[{", ".join(c._name for c in self)}]'
44+
return f'[{", ".join(c.real_name for c in self)}]'
4545

4646
def get_by_name(self, name: str) -> Channel | None:
4747
"""Get a channel from the list by `name`."""
4848
for channel in self:
49-
if channel._name == name:
49+
if channel.real_name == name:
5050
return channel
5151

5252
return None

app/objects/match.py

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ def __init__(
166166
self.has_public_history = has_public_history
167167

168168
self.host_id = host_id
169-
self._refs: set[Player] = set()
169+
self.referees: set[Player] = set()
170170

171171
self.map_id = map_id
172172
self.map_md5 = map_md5
@@ -232,12 +232,7 @@ def map_embed(self) -> str:
232232
@property
233233
def refs(self) -> set[Player]:
234234
"""Return all players with referee permissions."""
235-
refs = self._refs
236-
237-
if self.host is not None:
238-
refs.add(self.host)
239-
240-
return refs
235+
return self.referees | {self.host}
241236

242237
def __repr__(self) -> str:
243238
return f"<{self.name} ({self.id})>"

0 commit comments

Comments
 (0)