djangoldp-notification/djangoldp_notification/models.py

74 lines
2.3 KiB
Python
Raw Normal View History

2019-02-20 03:18:46 +00:00
import logging
from threading import Thread
import requests
from django.conf import settings
from django.contrib.admin.models import LogEntry
from django.contrib.sessions.models import Session
2019-01-09 09:27:54 +00:00
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from oidc_provider.models import Token
2019-02-28 01:21:03 +00:00
from djangoldp.fields import LDPUrlField
2019-02-20 03:18:46 +00:00
from djangoldp.models import Model
from djangoldp.permissions import InboxPermissions
2019-01-09 09:27:54 +00:00
class Notification(Model):
2019-01-31 09:44:41 +00:00
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='inbox')
2019-02-28 01:21:03 +00:00
author_user = LDPUrlField()
2019-03-01 04:20:21 +00:00
object = LDPUrlField()
2019-01-09 09:27:54 +00:00
type = models.CharField(max_length=255)
summary = models.TextField()
date = models.DateTimeField(auto_now_add=True)
read = models.BooleanField()
2019-01-09 09:27:54 +00:00
class Meta:
permissions = (
('view_notification', 'Read'),
('control_notification', 'Control'),
)
permission_classes=[InboxPermissions]
2019-01-09 09:27:54 +00:00
ordering = ['date']
def __str__(self):
return '{}'.format(self.type)
2019-01-31 09:44:41 +00:00
class Subscription(Model):
2019-01-31 09:44:41 +00:00
object = models.URLField()
inbox = models.URLField()
class Meta:
permissions = (
('view_notification', 'Read'),
('control_notification', 'Control'),
)
def __str__(self):
return '{}'.format(self.object)
2019-01-31 09:44:41 +00:00
# --- SUBSCRIPTION SYSTEM ---
2019-02-20 03:18:46 +00:00
@receiver(post_save, dispatch_uid="callback_notif")
def send_notification(sender, instance, **kwargs):
if (sender != Notification and sender != LogEntry and sender != Session and sender != Token):
2019-02-20 03:18:46 +00:00
threads = []
2019-03-06 10:38:58 +00:00
url = settings.BASE_URL + Model.resource_id(instance) + '/'
2019-02-20 03:18:46 +00:00
for subscription in Subscription.objects.filter(object=url):
process = Thread(target=send_request, args=[subscription.inbox, url])
process.start()
threads.append(process)
2019-03-06 10:38:58 +00:00
def send_request(target, object_iri):
2019-02-20 03:18:46 +00:00
try:
req = requests.post(target,
json={"@context": "https://cdn.happy-dev.fr/owl/hdcontext.jsonld",
"object": object_iri, "type": "update"},
headers={"Content-Type": "application/ld+json"})
2019-02-20 03:18:46 +00:00
except:
logging.error('Djangoldp_notifications: Error with request')
return True