import jinja2 from channels.db import database_sync_to_async from core.settings import PRIMARY_HOST from notifications.models import MessageTemplate TEMPLATE_VARS = ['ticket_name', 'ticket_uuid', 'ticket_id', 'ticket_url', 'current_state', 'previous_state', 'current_state_pretty', 'previous_state_pretty', 'event_slug', 'event_name', 'username', 'user_nick', 'web_host'] # TODO customer_name, tracking_code def limit_length(s, length=50): if len(s) > length: return s[:(length - 3)] + "..." return s def ticket_url(ticket): eventslug = ticket.event.slug if ticket.event else "37C3" # TODO 37C3 should not be hardcoded return f"https://{PRIMARY_HOST}/{eventslug}/ticket/{ticket.id}/" def render_template(template, **kwargs): try: environment = jinja2.Environment() environment.filters['limit_length'] = limit_length tmpl = MessageTemplate.objects.get(name=template) template = environment.from_string(tmpl.message) return template.render(**kwargs, web_host=PRIMARY_HOST) except MessageTemplate.DoesNotExist: return None def get_ticket_vars(ticket): states = list(ticket.state_changes.order_by('-timestamp')) return { 'ticket_name': ticket.name, 'ticket_uuid': ticket.short_uuid(), 'ticket_id': ticket.id, 'ticket_url': ticket_url(ticket), 'current_state': states[0].state if states else 'none', 'previous_state': states[1].state if len(states) > 1 else 'none', 'current_state_pretty': states[0].get_state_display() if states else 'none', 'previous_state_pretty': states[1].get_state_display() if len(states) > 1 else 'none', 'event_slug': ticket.event.slug if ticket.event else "37C3", # TODO 37C3 should not be hardcoded 'event_name': ticket.event.name if ticket.event else "37C3", } def render_auto_reply(ticket): return render_template('auto_reply', **get_ticket_vars(ticket)) def render_notification_new_ticket(ticket): return render_template('new_issue_notification', **get_ticket_vars(ticket)) def render_notification_reply_ticket(ticket): return render_template('reply_issue_notification', **get_ticket_vars(ticket)) async def render_notification_new_ticket_async(ticket): return await database_sync_to_async(render_notification_new_ticket)(ticket) async def render_notification_reply_ticket_async(ticket): return await database_sync_to_async(render_notification_reply_ticket)(ticket)