2022-06-24 11:29:10 +02:00
|
|
|
import json
|
2020-08-26 10:34:57 +02:00
|
|
|
|
2022-12-19 10:06:21 +01:00
|
|
|
from django.core.exceptions import ValidationError
|
2020-08-26 10:34:57 +02:00
|
|
|
from django.db import models
|
2022-06-24 11:29:10 +02:00
|
|
|
from django.db.models.signals import post_delete, post_save
|
|
|
|
from django.dispatch.dispatcher import receiver
|
2020-08-26 10:34:57 +02:00
|
|
|
|
2022-06-24 11:29:10 +02:00
|
|
|
from posthog.models.signals import mutable_receiver
|
2020-08-26 10:34:57 +02:00
|
|
|
from posthog.models.utils import generate_random_token
|
2022-06-24 11:29:10 +02:00
|
|
|
from posthog.redis import get_client
|
2020-08-26 10:34:57 +02:00
|
|
|
|
|
|
|
|
2024-08-15 11:46:47 +02:00
|
|
|
HOOK_EVENTS = ["action_performed"]
|
|
|
|
|
|
|
|
|
2022-12-19 10:06:21 +01:00
|
|
|
class Hook(models.Model):
|
2020-08-26 10:34:57 +02:00
|
|
|
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)
|
2020-10-22 10:58:32 +02:00
|
|
|
team = models.ForeignKey("posthog.Team", related_name="rest_hooks", on_delete=models.CASCADE)
|
2022-12-19 10:06:21 +01:00
|
|
|
event = models.CharField("Event", max_length=64, db_index=True)
|
2020-08-26 10:34:57 +02:00
|
|
|
resource_id = models.IntegerField(null=True, blank=True)
|
2022-12-19 10:06:21 +01:00
|
|
|
target = models.URLField("Target URL", max_length=255)
|
|
|
|
created = models.DateTimeField(auto_now_add=True)
|
|
|
|
updated = models.DateTimeField(auto_now=True)
|
|
|
|
|
|
|
|
def clean(self):
|
|
|
|
"""Validation for events."""
|
2024-08-15 11:46:47 +02:00
|
|
|
if self.event not in HOOK_EVENTS:
|
2022-12-19 10:06:21 +01:00
|
|
|
raise ValidationError("Invalid hook event {evt}.".format(evt=self.event))
|
2022-06-24 11:29:10 +02:00
|
|
|
|
|
|
|
|
|
|
|
@receiver(post_save, sender=Hook)
|
|
|
|
def hook_saved(sender, instance: Hook, created, **kwargs):
|
|
|
|
if instance.event == "action_performed":
|
|
|
|
get_client().publish(
|
2023-10-26 12:38:15 +02:00
|
|
|
"reload-action",
|
|
|
|
json.dumps({"teamId": instance.team_id, "actionId": instance.resource_id}),
|
2022-06-24 11:29:10 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
@mutable_receiver(post_delete, sender=Hook)
|
|
|
|
def hook_deleted(sender, instance: Hook, **kwargs):
|
|
|
|
if instance.event == "action_performed":
|
2023-10-26 12:38:15 +02:00
|
|
|
get_client().publish(
|
|
|
|
"drop-action",
|
|
|
|
json.dumps({"teamId": instance.team_id, "actionId": instance.resource_id}),
|
|
|
|
)
|