0
0
mirror of https://github.com/PostHog/posthog.git synced 2024-11-28 18:26:15 +01:00
posthog/ee/models/hook.py
Michael Matloka b9f00b2710
Fix webhooks specifity (#3463)
* Fix webhooks specifity

* Make REST hook firing monitoring better reflect reality
2021-02-24 23:14:02 +01:00

37 lines
1.5 KiB
Python

from typing import Optional
import statsd
from django.conf import settings
from django.db import models
from rest_hooks.models import AbstractHook
from ee.tasks.hooks import DeliverHook
from posthog.models.team import Team
from posthog.models.utils import generate_random_token
class Hook(AbstractHook):
id = models.CharField(primary_key=True, max_length=50, default=generate_random_token)
user = models.ForeignKey("posthog.User", related_name="rest_hooks", on_delete=models.CASCADE)
team = models.ForeignKey("posthog.Team", related_name="rest_hooks", on_delete=models.CASCADE)
resource_id = models.IntegerField(null=True, blank=True)
def find_and_fire_hook(
event_name: str, instance: models.Model, user_override: Team, payload_override: Optional[dict] = None,
):
if not user_override.organization.is_feature_available("zapier"):
return
hooks = Hook.objects.filter(event=event_name, team=user_override)
if event_name == "action_performed":
# action_performed is a resource_id-filterable hook
hooks = hooks.filter(models.Q(resource_id=instance.pk))
for hook in hooks:
statsd.Counter("%s_posthog_cloud_hooks_rest_fired" % (settings.STATSD_PREFIX,)).increment()
hook.deliver_hook(instance, payload_override)
def deliver_hook_wrapper(target, payload, instance, hook):
# pass IDs not objects because using pickle for objects is a bad thing
DeliverHook.apply_async(kwargs=dict(target=target, payload=payload, hook_id=hook.id))