Skip to content

Commit

Permalink
Merge pull request #39 from RiiConnect24/sourcery/master
Browse files Browse the repository at this point in the history
  • Loading branch information
malmeloo authored Oct 28, 2023
2 parents f9c7079 + 1976487 commit 145bdb8
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 62 deletions.
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:
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}"
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())}')

@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

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)
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

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}'

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:
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())

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'):
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":
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"

@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"

@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"

@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

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)


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())


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()]


def parse_rankings(fp, max_results):
games = []
with open(fp) as file:
for line in file.readlines():
for line in file:
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
]:
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

0 comments on commit 145bdb8

Please sign in to comment.