Skip to content

Commit

Permalink
Centralise cache directory management
Browse files Browse the repository at this point in the history
  • Loading branch information
malmeloo committed May 31, 2023
1 parent 5551658 commit 5c16cc9
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 14 deletions.
17 changes: 9 additions & 8 deletions menus.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
from sentry_sdk import configure_scope

from riitag import oauth2, user, watcher, presence
from riitag.util import get_cache


# Get resource when frozen with PyInstaller
Expand Down Expand Up @@ -194,12 +195,12 @@ def skip_loading(_):

@property
def is_token_cached(self):
return os.path.isfile('cache/token.json')
return os.path.isfile(get_cache('token.json'))

def _refresh_token(self, token):
try:
token.refresh()
token.save('cache/token.json')
token.save(get_cache('token.json'))

self.app.token = token
self.app.user = token.get_user()
Expand Down Expand Up @@ -237,7 +238,7 @@ def _connect_presence(self):

def _login(self):
if self.is_token_cached:
with open('cache/token.json', 'r') as file:
with open(get_cache('token.json'), 'r') as file:
token_data = json.load(file)
try:
token = oauth2.OAuth2Token(self.app.oauth_client, **token_data)
Expand Down Expand Up @@ -273,7 +274,7 @@ def __init__(self, *args, **kwargs):

self.state = 'setup_start'

if not os.path.isfile('cache/token.json'): # new user
if not os.path.isfile(get_cache('token.json')): # new user
self.setup_start_layout = Window(FormattedTextControl(HTML(
'\n\n\n<b>Hello!</b> It looks like this is your first time using this program.\n'
'No worries! Let\'s get your Discord account linked up first.\n\n\n'
Expand Down Expand Up @@ -344,7 +345,7 @@ def _get_token(self):
self.update()

token = self.app.oauth_client.get_token(code)
token.save('cache/token.json')
token.save(get_cache('token.json'))
self.app.token = token

self.app.user = token.get_user()
Expand Down Expand Up @@ -509,7 +510,7 @@ def decrease_preference(event):

def _logout_callback(self, confirm):
if confirm:
os.remove('cache/token.json')
os.remove(get_cache('token.json'))
self.app.exit()

def _logout(self):
Expand Down Expand Up @@ -545,13 +546,13 @@ def _modify_setting(self, mode):
is_modified = True
self.app.preferences.presence_timeout = self.settings_pres_timeout_button.value

self.app.preferences.save('cache/prefs.json')
self.app.preferences.save(get_cache('prefs.json'))

return is_modified

def _reset_preferences(self):
self.app.preferences.reset()
self.app.preferences.save('cache/prefs.json')
self.app.preferences.save(get_cache('prefs.json'))

self.settings_pres_timeout_button.value = self.app.preferences.presence_timeout
self.settings_pres_timeout_button.update()
Expand Down
26 changes: 26 additions & 0 deletions riitag/util.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import os
import platform

CACHE_DIR_NAME = 'riitag-rpc'


def get_cache_dir():
plat = platform.system()
if plat == 'Windows':
path = os.getenv('LOCALAPPDATA')
elif plat == 'Linux':
fallback = os.path.join(os.getenv('HOME'), '.cache')
path = os.getenv('XDG_CACHE_HOME', fallback)
elif plat == 'Darwin':
fallback = os.path.join(os.getenv('HOME'), 'Library/Caches')
path = os.getenv('XDG_CACHE_HOME', fallback)
else:
raise OSError(f'Platform unsupported: {plat}')

path = os.path.join(path, CACHE_DIR_NAME)
os.makedirs(path, exist_ok=True)
return path


def get_cache(filename):
return os.path.join(get_cache_dir(), filename)
16 changes: 10 additions & 6 deletions start.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import menus
from riitag import oauth2, user, watcher, presence, preferences
from riitag.util import get_cache

nest_asyncio.apply()

Expand Down Expand Up @@ -65,11 +66,11 @@ def on_thread_error(args):
threading.excepthook = on_thread_error

try:
os.makedirs('cache/', exist_ok=True)
# prepare cache dir early so we can spot errors sooner
get_cache('')
except OSError:
print('ERROR: Could not create cache directory.')
print('Please check file permissions and try again.')
print('Do NOT save this program in a system directory!')
print()
print('Press enter to exit.')
input()
Expand All @@ -90,12 +91,15 @@ def resource_path(relative_path):

def get_user_id():
try:
with open(resource_path('cache/_uid'), 'r') as f:
with open(get_cache('_uid'), 'r') as f:
return f.read().strip()
except FileNotFoundError:
uid = str(uuid.uuid4())
with open(resource_path('cache/_uid'), 'w+') as f:
f.write(uid)
try:
with open(get_cache('_uid'), 'w+') as f:
f.write(uid)
except:
return None
return uid


Expand Down Expand Up @@ -126,7 +130,7 @@ def __init__(self, *args, **kwargs):
self._current_menu: menus.Menu | None = None
self._float_message_layout = None

self.preferences = preferences.Preferences.load('cache/prefs.json')
self.preferences = preferences.Preferences.load(get_cache('prefs.json'))
self.oauth_client = oauth2.OAuth2Client(CONFIG.get('oauth2'))
self.rpc_handler = presence.RPCHandler(
CONFIG.get('rpc', {}).get('client_id')
Expand Down

0 comments on commit 5c16cc9

Please sign in to comment.