Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sourcery refactored master branch #39

Merged
merged 2 commits into from
Oct 28, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions menus.py
Original file line number Diff line number Diff line change
Expand Up @@ -373,8 +373,7 @@ def __init__(self, *args, **kwargs):

self.riitag_info = user.RiitagInfo() # placeholder

discord_user = self.app.user
if discord_user:
if discord_user := self.app.user:
malmeloo marked this conversation as resolved.
Show resolved Hide resolved
with configure_scope() as scope:
scope.set_tag('discord.user', f'{discord_user.username}#{discord_user.discriminator}')
scope.set_tag('discord.id', discord_user.id)
Expand Down Expand Up @@ -585,7 +584,7 @@ def _update_riitag(self, riitag: user.RiitagInfo):

def view_riitag(self):
client_id = self.app.user.id
tag_url = "https://tag.rc24.xyz/" + client_id
tag_url = f"https://tag.rc24.xyz/{client_id}"
malmeloo marked this conversation as resolved.
Show resolved Hide resolved
try:
webbrowser.open(tag_url)
except webbrowser.Error:
Expand Down
24 changes: 7 additions & 17 deletions riitag/oauth2.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,12 @@ def __init__(self, client: OAuth2Client, **kwargs):
self.last_refresh = kwargs.pop('last_refresh', time.time())

if kwargs:
raise ValueError('Unexpected arguments: ' + str(kwargs.keys()))
raise ValueError(f'Unexpected arguments: {str(kwargs.keys())}')
malmeloo marked this conversation as resolved.
Show resolved Hide resolved

@property
def needs_refresh(self):
curr_time = time.time()
if curr_time - self.last_refresh > self.expires_in:
return True

return False
return curr_time - self.last_refresh > self.expires_in
malmeloo marked this conversation as resolved.
Show resolved Hide resolved

def save(self, fn):
data = {
Expand Down Expand Up @@ -86,7 +83,7 @@ def get_user(self) -> User:
'Content-Type': 'application/json',
'Authorization': f'Bearer {self.access_token}'
}
r = requests.get(API_ENDPOINT + '/users/@me', headers=headers)
r = requests.get(f'{API_ENDPOINT}/users/@me', headers=headers)
malmeloo marked this conversation as resolved.
Show resolved Hide resolved
r.raise_for_status()

return User(**r.json())
Expand All @@ -102,13 +99,9 @@ def do_GET(self):
query_str = urllib.parse.urlparse(self.path).query
query = urllib.parse.parse_qs(query_str)
code = query.get('code')
if not code:
self.handle_400()
return
elif len(code) != 1:
if not code or len(code) != 1:
self.handle_400()
return

malmeloo marked this conversation as resolved.
Show resolved Hide resolved
self.server.code = code[0]

self.send_response(200)
Expand Down Expand Up @@ -171,15 +164,14 @@ def auth_url(self):
}
query_str = urllib.parse.urlencode(query)

return AUTHORIZE_ENDPOINT + '?' + query_str
return f'{AUTHORIZE_ENDPOINT}?{query_str}'
malmeloo marked this conversation as resolved.
Show resolved Hide resolved

def wait_for_code(self):
if not self._http_server:
raise RuntimeError('Server not yet started.')

while True:
code = self._http_server.code
if code:
if code := self._http_server.code:
malmeloo marked this conversation as resolved.
Show resolved Hide resolved
return code

def get_token(self, code):
Expand All @@ -197,9 +189,7 @@ def get_token(self, code):
r = requests.post(TOKEN_ENDPOINT, data=payload, headers=headers)
r.raise_for_status()

token = OAuth2Token(self, **r.json())

return token
return OAuth2Token(self, **r.json())
malmeloo marked this conversation as resolved.
Show resolved Hide resolved

def start_server(self, port: int) -> None:
if self._http_server: # already initialized
Expand Down
3 changes: 1 addition & 2 deletions riitag/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,8 +183,7 @@ def fetch_riitag(self):
return

data = r.json()
error = data.get('error')
if error:
if error := data.get('error'):
malmeloo marked this conversation as resolved.
Show resolved Hide resolved
raise RiitagNotFoundError(error)

riitag = RiitagInfo(**data)
Expand Down
54 changes: 14 additions & 40 deletions tools/asset_uploader/asset_uploader.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,7 @@ def __init__(self, game_id, play_count):
@property
def region(self):
region_char = self.game_id[3]
if region_char == "P":
return "EN"
elif region_char == "E":
if region_char == "E":
malmeloo marked this conversation as resolved.
Show resolved Hide resolved
return "US"
elif region_char == "J":
return "JA"
Expand All @@ -58,28 +56,15 @@ def console(self):
code = self.game_id[0]

# not complete, needs support for console prefixes.
if code in ["R", "S"]:
return "wii"
elif code in ["A", "B"]:
return "wiiu"
else:
return "wii"
return "wii" if code in ["R", "S"] or code not in ["A", "B"] else "wiiu"
malmeloo marked this conversation as resolved.
Show resolved Hide resolved

@property
def cover_type(self):
if self.console in ["ds", "3ds"]:
return "box"
else:
return "cover3D"
return "box" if self.console in ["ds", "3ds"] else "cover3D"
malmeloo marked this conversation as resolved.
Show resolved Hide resolved

@property
def img_extension(self):
if self.console == "wii":
return "png"
elif self.console != "wii" and self.cover_type == "cover":
return "jpg"
else:
return "png"
return "png" if self.console == "wii" or self.cover_type != "cover" else "jpg"
malmeloo marked this conversation as resolved.
Show resolved Hide resolved

@property
def cover_url(self):
Expand All @@ -99,10 +84,7 @@ def __init__(self, id, type, name):
self.name = name

def __eq__(self, other):
if not isinstance(other, DiscordAsset):
return False

return self.name == other.name
return self.name == other.name if isinstance(other, DiscordAsset) else False
malmeloo marked this conversation as resolved.
Show resolved Hide resolved

def remove(self):
headers = {
Expand All @@ -120,12 +102,7 @@ def remove(self):

def download_cover(game: RiitagGame):
r = requests.get(game.cover_url)
if r.status_code != 200:
return None

file = BytesIO(r.content)

return file
return None if r.status_code != 200 else BytesIO(r.content)
malmeloo marked this conversation as resolved.
Show resolved Hide resolved


def upload_asset(file, name):
Expand All @@ -143,9 +120,7 @@ def upload_asset(file, name):
r = requests.post(ASSET_UPLOAD_URL, headers=headers, json=payload)
r.raise_for_status()

asset = DiscordAsset(**r.json())

return asset
return DiscordAsset(**r.json())
malmeloo marked this conversation as resolved.
Show resolved Hide resolved


def get_assets():
Expand All @@ -157,15 +132,13 @@ def get_assets():
r = requests.get(ASSET_UPLOAD_URL, headers=headers)
r.raise_for_status()

assets = [DiscordAsset(**data) for data in r.json()]

return assets
return [DiscordAsset(**data) for data in r.json()]
malmeloo marked this conversation as resolved.
Show resolved Hide resolved


def parse_rankings(fp, max_results):
games = []
with open(fp) as file:
for line in file.readlines():
for line in file:
malmeloo marked this conversation as resolved.
Show resolved Hide resolved
count, game_id = line.split()
game = RiitagGame(
play_count=int(count),
Expand Down Expand Up @@ -207,8 +180,9 @@ def main():
cover.seek(0)

if AUTO_UPLOAD:
existing_assets = [asset for asset in app_assets if asset.name == asset_name]
if existing_assets:
if existing_assets := [
asset for asset in app_assets if asset.name == asset_name
]:
malmeloo marked this conversation as resolved.
Show resolved Hide resolved
for num, asset in enumerate(existing_assets):
print(f"({n + 1}/{DOWNLOAD_COUNT}) Removing dupe asset {num}/{len(existing_assets)}...",
end="\r", flush=True)
Expand All @@ -225,14 +199,14 @@ def main():
failed_games.append(game)
status = "FAILED"

print("ERROR: " + e.response.text)
print(f"ERROR: {e.response.text}")

print(f"({n + 1}/{DOWNLOAD_COUNT}) {game.game_id} finished ({status})")

print()
print(f"A total of {len(games) - len(failed_games)} assets have been processed.")
if failed_games:
print(f"These games failed to upload and may require manual intervention:")
print("These games failed to upload and may require manual intervention:")
for game in failed_games:
print(f"=> {game.game_id} - {game.cover_url}")

Expand Down
Loading