Clean up item loading code

This commit is contained in:
Tim Van Baak 2020-08-06 15:38:24 -07:00
parent a9e313225f
commit 024d81336d
3 changed files with 42 additions and 16 deletions

View File

@ -106,8 +106,7 @@ def deactivate():
params = request.get_json() params = request.get_json()
if 'source' not in params and 'itemid' not in params: if 'source' not in params and 'itemid' not in params:
logger.error("Bad request params: {}".format(params)) logger.error("Bad request params: {}".format(params))
item = loader.WritethroughDict(os.path.join( item = loader.load_item(params['source'], params['itemid'])
DUNGEON_PATH, params['source'], params['itemid'] + '.item'))
if item['active']: if item['active']:
logger.debug(f"Deactivating {params['source']}/{params['itemid']}") logger.debug(f"Deactivating {params['source']}/{params['itemid']}")
item['active'] = False item['active'] = False
@ -118,8 +117,7 @@ def punt():
params = request.get_json() params = request.get_json()
if 'source' not in params and 'itemid' not in params: if 'source' not in params and 'itemid' not in params:
logger.error("Bad request params: {}".format(params)) logger.error("Bad request params: {}".format(params))
item = loader.WritethroughDict(os.path.join( item = loader.load_item(params['source'], params['itemid'])
DUNGEON_PATH, params['source'], params['itemid'] + '.item'))
tomorrow = datetime.now() + timedelta(days=1) tomorrow = datetime.now() + timedelta(days=1)
morning = datetime(tomorrow.year, tomorrow.month, tomorrow.day, 6, 0, 0) morning = datetime(tomorrow.year, tomorrow.month, tomorrow.day, 6, 0, 0)
til_then = morning.timestamp() - item['created'] til_then = morning.timestamp() - item['created']
@ -134,8 +132,7 @@ def mass_deactivate():
for info in params.get('items', []): for info in params.get('items', []):
source = info['source'] source = info['source']
itemid = info['itemid'] itemid = info['itemid']
item = loader.WritethroughDict(os.path.join( item = loader.load_item(source, itemid)
DUNGEON_PATH, source, itemid + ".item"))
if item['active']: if item['active']:
logger.debug(f"Deactivating {info['source']}/{info['itemid']}") logger.debug(f"Deactivating {info['source']}/{info['itemid']}")
item['active'] = False item['active'] = False

View File

@ -1,18 +1,42 @@
import os import os
import json import json
from inquisitor.configs import DUNGEON_PATH from inquisitor.configs import DUNGEON_PATH
from inquisitor import error from inquisitor import error
from inquisitor import timestamp from inquisitor import timestamp
class WritethroughDict(): class WritethroughDict():
"""A wrapper for a dictionary saved to the disk.""" """A wrapper for a dictionary saved to the file system."""
def __init__(self, path):
@staticmethod
def create(path, item):
"""
Creates a writethrough dictionary from a dictionary in memory and
initializes a file to save it.
"""
if os.path.isfile(path):
raise FileExistsError(path)
wd = WritethroughDict(path, item)
wd.flush()
return wd
@staticmethod
def load(path):
"""
Creates a writethrough dictionary from an existing file in the
file system.
"""
if not os.path.isfile(path): if not os.path.isfile(path):
raise FileNotFoundError(path) raise FileNotFoundError(path)
self.path = path
with open(path) as f: with open(path) as f:
self.item = json.loads(f.read()) item = json.load(f)
return WritethroughDict(path, item)
def __init__(self, path, item):
self.path = path
self.item = item
def __getitem__(self, key): def __getitem__(self, key):
return self.item[key] return self.item[key]
@ -40,10 +64,17 @@ class WritethroughDict():
with open(self.path, 'w', encoding="utf8") as f: with open(self.path, 'w', encoding="utf8") as f:
f.write(s) f.write(s)
def load_state(source_name): def load_state(source_name):
"""Loads the state dictionary for a source.""" """Loads the state dictionary for a source."""
state_path = os.path.join(DUNGEON_PATH, source_name, "state") state_path = os.path.join(DUNGEON_PATH, source_name, "state")
return WritethroughDict(state_path) return WritethroughDict.load(state_path)
def load_item(source_name, item_id):
"""Loads an item from a source."""
item_path = os.path.join(DUNGEON_PATH, source_name, f'{item_id}.item')
return WritethroughDict.load(item_path)
def load_items(source_name): def load_items(source_name):
""" """
@ -55,8 +86,7 @@ def load_items(source_name):
for filename in os.listdir(cell_path): for filename in os.listdir(cell_path):
if filename.endswith('.item'): if filename.endswith('.item'):
try: try:
path = os.path.join(cell_path, filename) item = load_item(source_name, filename[:-5])
item = WritethroughDict(path)
items[item['id']] = item items[item['id']] = item
except Exception: except Exception:
errors.append(filename) errors.append(filename)
@ -74,8 +104,7 @@ def load_active_items():
for filename in os.listdir(cell_path): for filename in os.listdir(cell_path):
if filename.endswith('.item'): if filename.endswith('.item'):
try: try:
path = os.path.join(cell_path, filename) item = load_item(cell_name, filename[:-5])
item = WritethroughDict(path)
# The time-to-show field hides items until an expiry date. # The time-to-show field hides items until an expiry date.
if 'tts' in item: if 'tts' in item:
tts_date = item['created'] + item['tts'] tts_date = item['created'] + item['tts']

View File

@ -208,7 +208,7 @@ def item_callback(source_name, itemid):
raise ImportError(f"Missing callback in '{source_name}'") raise ImportError(f"Missing callback in '{source_name}'")
# Load the source state and the origin item # Load the source state and the origin item
state = loader.load_state(source_name) state = loader.load_state(source_name)
item = loader.WritethroughDict(os.path.join(DUNGEON_PATH, source_name, itemid + ".item")) item = loader.load_item(source_name, itemid)
# Execute callback # Execute callback
source_module.callback(state, item) source_module.callback(state, item)
# Save any changes # Save any changes