Add create and delete triggers

This commit is contained in:
Tim Van Baak 2020-08-06 23:48:10 -07:00
parent c116476487
commit 364480c08d
4 changed files with 56 additions and 7 deletions

View File

@ -150,8 +150,7 @@ def command_feed(args):
if errors: if errors:
items.insert(0, { items.insert(0, {
'id': 'read-errors', 'title': '{} read errors: {}'.format(len(errors), ' '.join(errors)),
'title': '{} read errors'.format(len(errors)),
'body': "\n".join(errors) 'body': "\n".join(errors)
}) })
@ -176,7 +175,7 @@ def command_feed(args):
print("| {0:<{1}} |".format(info1, width - 4)) print("| {0:<{1}} |".format(info1, width - 4))
created = timestamp.stamp_to_readable(item['created']) if 'created' in item else "" created = timestamp.stamp_to_readable(item['created']) if 'created' in item else ""
info2 = "{0} {1} {2}".format( info2 = "{0} {1} {2}".format(
item['source'], item['id'], created) item.get('source', ''), item.get('id', ''), created)
print("| {0:<{1}} |".format(info2, width - 4)) print("| {0:<{1}} |".format(info2, width - 4))
print('+' + (width - 2) * '-' + '+') print('+' + (width - 2) * '-' + '+')
print() print()

View File

@ -41,6 +41,9 @@ class WritethroughDict():
def __getitem__(self, key): def __getitem__(self, key):
return self.item[key] return self.item[key]
def get(self, *args, **kwargs):
return self.item.get(*args, **kwargs)
def __setitem__(self, key, value): def __setitem__(self, key, value):
self.item[key] = value self.item[key] = value
self.flush() self.flush()

View File

@ -62,7 +62,7 @@ def update_sources(*source_names):
# Update the source # Update the source
try: try:
logger.info(f'Updating source "{source_name}"') logger.info(f'Updating source "{source_name}"')
update_source(source_name, source_module.fetch_new) update_source(source_name, source_module)
except Exception: except Exception:
error.as_item( error.as_item(
f'Error updating source "{source_name}"', f'Error updating source "{source_name}"',
@ -101,7 +101,7 @@ def load_source(source_name):
os.chdir(cwd) os.chdir(cwd)
def update_source(source_name, fetch_new): def update_source(source_name, source):
""" """
Attempts to update the given source. Raises an exception if the source does. Attempts to update the given source. Raises an exception if the source does.
""" """
@ -111,7 +111,7 @@ def update_source(source_name, fetch_new):
# Get the feed items from the source's fetch method. # Get the feed items from the source's fetch method.
state = loader.load_state(source_name) state = loader.load_state(source_name)
fetched = fetch_new(state) fetched = source.fetch_new(state)
state.flush() state.flush()
logger.debug(f'Fetched {len(fetched)} items') logger.debug(f'Fetched {len(fetched)} items')
fetched_items = {item['id']: item for item in fetched} fetched_items = {item['id']: item for item in fetched}
@ -130,9 +130,12 @@ def update_source(source_name, fetch_new):
new_items.append(item) new_items.append(item)
# Write all the new items to the source's cell. # Write all the new items to the source's cell.
has_create_handler = hasattr(source, 'on_create')
for item in new_items: for item in new_items:
item_source = item.get('source', source_name) item_source = item.get('source', source_name)
loader.new_item(item_source, item) created_item = loader.new_item(item_source, item)
if has_create_handler:
source.on_create(state, created_item)
# Update the other items using the fetched items' values. # Update the other items using the fetched items' values.
for new_item in updated_items: for new_item in updated_items:
@ -152,6 +155,7 @@ def update_source(source_name, fetch_new):
# fetch) and inactive. Some item fields can change this basic behavior. # fetch) and inactive. Some item fields can change this basic behavior.
del_count = 0 del_count = 0
now = timestamp.now() now = timestamp.now()
has_delete_handler = hasattr(source, 'on_delete')
fetched_ids = [item['id'] for item in updated_items] fetched_ids = [item['id'] for item in updated_items]
old_item_ids = [ old_item_ids = [
item_id for item_id in prior_ids item_id for item_id in prior_ids
@ -173,6 +177,8 @@ def update_source(source_name, fetch_new):
remove = True remove = True
# Items to be removed are deleted # Items to be removed are deleted
if remove: if remove:
if has_delete_handler:
source.on_delete(state, item)
del_count += 1 del_count += 1
file_path = os.path.join(DUNGEON_PATH, item['source'], item['id'] + ".item") file_path = os.path.join(DUNGEON_PATH, item['source'], item['id'] + ".item")
try: try:

41
sources/triggerdemo.py Normal file
View File

@ -0,0 +1,41 @@
"""
Demonstrates the behavior of the on_create and on_delete triggers.
The items it creates spawn dummy messages on creation and deletion.
It assumes the dungeon is located at ./dungeon.
"""
# Standard library imports
from datetime import datetime
import json
import random
def fetch_new(state):
if state.get('return_item'):
state['return_item'] = False
return [{
'source': 'triggerdemo',
'id': 'triggerdemoitem',
'title': 'This is the trigger demo item'
}]
else:
state['return_item'] = True
return []
def on_create(state, item):
with open('dungeon/inquisitor/triggerdemo_create.item', 'w') as f:
json.dump({
'source': 'inquisitor',
'id': 'triggerdemo_create.item',
'title': 'Trigger demo on_create item',
'active': True,
}, f)
def on_delete(state, item):
with open('dungeon/inquisitor/triggerdemo_delete.item', 'w') as f:
json.dump({
'source': 'inquisitor',
'id': 'triggerdemo_delete.item',
'title': 'Trigger demo on_delete item',
'active': True,
}, f)