2019-02-20 03:18:46 +00:00
|
|
|
import requests
|
|
|
|
import logging
|
|
|
|
import datetime
|
|
|
|
from threading import Thread
|
2019-01-09 09:27:54 +00:00
|
|
|
from django.db import models
|
|
|
|
from django.conf import settings
|
2019-01-31 09:44:41 +00:00
|
|
|
from django.db.models.signals import post_save
|
|
|
|
from django.dispatch import receiver
|
2019-01-09 09:27:54 +00:00
|
|
|
from django.contrib.auth.models import User
|
2019-01-31 09:44:41 +00:00
|
|
|
from django.contrib.admin.models import LogEntry
|
2019-02-20 03:18:46 +00:00
|
|
|
from djangoldp.models import Model
|
2019-01-09 09:27:54 +00:00
|
|
|
|
|
|
|
class Notification(models.Model):
|
2019-01-31 09:44:41 +00:00
|
|
|
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='inbox')
|
|
|
|
author_user = models.URLField()
|
2019-01-09 09:27:54 +00:00
|
|
|
object = models.URLField()
|
|
|
|
type = models.CharField(max_length=255)
|
|
|
|
summary = models.TextField()
|
|
|
|
date = models.DateTimeField(auto_now_add=True)
|
|
|
|
read = models.BooleanField()
|
|
|
|
class Meta:
|
|
|
|
permissions = (
|
|
|
|
('view_notification', 'Read'),
|
|
|
|
('control_notification', 'Control'),
|
|
|
|
)
|
|
|
|
ordering = ['date']
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return '{}'.format(self.type)
|
2019-01-31 09:44:41 +00:00
|
|
|
|
|
|
|
class Subscription(models.Model):
|
|
|
|
object = models.URLField()
|
|
|
|
inbox = models.URLField()
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
permissions = (
|
|
|
|
('view_notification', 'Read'),
|
|
|
|
('control_notification', 'Control'),
|
|
|
|
)
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return '{}'.format(self.object)
|
|
|
|
|
|
|
|
# --- 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):
|
|
|
|
threads = []
|
|
|
|
url = "http://127.0.0.1:8000" + Model.get_absolute_url(instance) + '/' # TODO : get host
|
|
|
|
for subscription in Subscription.objects.filter(object=url):
|
|
|
|
process = Thread(target=send_request, args=[subscription.inbox, url])
|
|
|
|
process.start()
|
|
|
|
threads.append(process)
|
|
|
|
def send_request(target, object):
|
|
|
|
try:
|
|
|
|
req=requests.post(target,
|
|
|
|
json={"@context":"https://cdn.happy-dev.fr/owl/hdcontext.jsonld",
|
|
|
|
"object": object, "type": "system", "read": False},
|
|
|
|
headers={"Content-Type": "application/ld+json"})
|
|
|
|
except:
|
|
|
|
logging.error('Djangoldp_notifications: Error with request')
|
|
|
|
return True
|