2018-07-30 14:23:49 -04:00
|
|
|
import datetime
|
2018-05-30 11:19:10 -04:00
|
|
|
|
2018-07-30 16:33:37 -04:00
|
|
|
from django.conf import settings
|
2018-07-16 17:09:21 -04:00
|
|
|
from django.contrib.contenttypes.models import ContentType
|
2018-05-30 11:19:10 -04:00
|
|
|
|
2018-11-02 15:20:08 -04:00
|
|
|
from extras.models import Webhook
|
2018-07-30 14:23:49 -04:00
|
|
|
from utilities.api import get_serializer_for_model
|
2019-10-04 12:08:48 -04:00
|
|
|
from .constants import *
|
2018-07-30 14:23:49 -04:00
|
|
|
|
|
|
|
|
2019-03-24 15:35:42 -04:00
|
|
|
def enqueue_webhooks(instance, user, request_id, action):
|
2018-07-30 14:23:49 -04:00
|
|
|
"""
|
|
|
|
Find Webhook(s) assigned to this instance + action and enqueue them
|
|
|
|
to be processed
|
|
|
|
"""
|
2019-04-17 14:19:57 -04:00
|
|
|
if not settings.WEBHOOKS_ENABLED or instance._meta.label.lower() not in WEBHOOK_MODELS:
|
2018-07-30 16:33:37 -04:00
|
|
|
return
|
|
|
|
|
2018-08-07 15:41:31 -04:00
|
|
|
# Retrieve any applicable Webhooks
|
|
|
|
action_flag = {
|
|
|
|
OBJECTCHANGE_ACTION_CREATE: 'type_create',
|
|
|
|
OBJECTCHANGE_ACTION_UPDATE: 'type_update',
|
|
|
|
OBJECTCHANGE_ACTION_DELETE: 'type_delete',
|
|
|
|
}[action]
|
2018-07-30 14:23:49 -04:00
|
|
|
obj_type = ContentType.objects.get_for_model(instance.__class__)
|
2018-08-07 15:41:31 -04:00
|
|
|
webhooks = Webhook.objects.filter(obj_type=obj_type, enabled=True, **{action_flag: True})
|
|
|
|
|
|
|
|
if webhooks.exists():
|
2018-07-30 14:23:49 -04:00
|
|
|
# Get the Model's API serializer class and serialize the object
|
|
|
|
serializer_class = get_serializer_for_model(instance.__class__)
|
|
|
|
serializer_context = {
|
|
|
|
'request': None,
|
|
|
|
}
|
|
|
|
serializer = serializer_class(instance, context=serializer_context)
|
|
|
|
|
|
|
|
# We must only import django_rq if the Webhooks feature is enabled.
|
|
|
|
# Only if we have gotten to ths point, is the feature enabled
|
|
|
|
from django_rq import get_queue
|
|
|
|
webhook_queue = get_queue('default')
|
|
|
|
|
|
|
|
# enqueue the webhooks:
|
|
|
|
for webhook in webhooks:
|
|
|
|
webhook_queue.enqueue(
|
|
|
|
"extras.webhooks_worker.process_webhook",
|
|
|
|
webhook,
|
|
|
|
serializer.data,
|
2018-12-04 00:40:54 -05:00
|
|
|
instance._meta.model_name,
|
2018-07-30 14:23:49 -04:00
|
|
|
action,
|
2019-03-24 15:31:12 -04:00
|
|
|
str(datetime.datetime.now()),
|
2019-03-24 15:35:42 -04:00
|
|
|
user.username,
|
|
|
|
request_id
|
2018-07-30 14:23:49 -04:00
|
|
|
)
|