core/services/notify.py

46 lines
1.5 KiB
Python
Raw Normal View History

2023-10-05 18:46:18 +00:00
import json
2023-12-17 20:30:20 +00:00
2023-10-23 14:47:11 +00:00
from services.rediscache import redis
2023-10-05 18:46:18 +00:00
2024-02-21 16:14:58 +00:00
async def notify_reaction(reaction, action: str = 'create'):
channel_name = 'reaction'
data = {'payload': reaction, 'action': action}
2023-10-05 18:46:18 +00:00
try:
await redis.publish(channel_name, json.dumps(data))
except Exception as e:
2024-02-21 16:14:58 +00:00
print(f'[services.notify] Failed to publish to channel {channel_name}: {e}')
2023-10-05 18:46:18 +00:00
2024-02-21 16:14:58 +00:00
async def notify_shout(shout, action: str = 'update'):
channel_name = 'shout'
data = {'payload': shout, 'action': action}
2023-10-05 18:46:18 +00:00
try:
await redis.publish(channel_name, json.dumps(data))
except Exception as e:
2024-02-21 16:14:58 +00:00
print(f'[services.notify] Failed to publish to channel {channel_name}: {e}')
2023-10-05 18:46:18 +00:00
2024-02-21 16:14:58 +00:00
async def notify_follower(follower: dict, author_id: int, action: str = 'follow'):
channel_name = f'follower:{author_id}'
2023-10-05 18:46:18 +00:00
try:
2024-01-22 23:47:23 +00:00
# Simplify dictionary before publishing
2024-02-21 16:14:58 +00:00
simplified_follower = {k: follower[k] for k in ['id', 'name', 'slug', 'pic']}
2024-01-22 23:47:23 +00:00
2024-02-21 16:14:58 +00:00
data = {'payload': simplified_follower, 'action': action}
2024-01-22 23:47:23 +00:00
# Convert data to JSON string
json_data = json.dumps(data)
# Ensure the data is not empty before publishing
if not json_data:
2024-02-21 16:14:58 +00:00
raise ValueError('Empty data to publish.')
2024-01-22 23:47:23 +00:00
# Use the 'await' keyword when publishing
await redis.publish(channel_name, json_data)
2023-10-05 18:46:18 +00:00
except Exception as e:
2024-01-22 23:47:23 +00:00
# Log the error and re-raise it
2024-02-21 16:14:58 +00:00
print(f'[services.notify] Failed to publish to channel {channel_name}: {e}')
2024-01-22 23:47:23 +00:00
raise