From fe98c26b5a186587078dfec7012ba41baa662532 Mon Sep 17 00:00:00 2001
From: Matthieu Fesselier <matthieu.fesselier@gmail.com>
Date: Thu, 31 Jan 2019 16:44:41 +0700
Subject: [PATCH] update: add subscription system

---
 djangoldp_notification/admin.py               |  3 +-
 djangoldp_notification/factories.py           |  2 +-
 .../migrations/0001_initial.py                | 17 +++++--
 djangoldp_notification/models.py              | 47 +++++++++++++++++--
 djangoldp_notification/settings.py            |  1 +
 djangoldp_notification/urls.py                |  7 +--
 6 files changed, 65 insertions(+), 12 deletions(-)
 create mode 100644 djangoldp_notification/settings.py

diff --git a/djangoldp_notification/admin.py b/djangoldp_notification/admin.py
index 783f0f0..6a90aa5 100644
--- a/djangoldp_notification/admin.py
+++ b/djangoldp_notification/admin.py
@@ -1,4 +1,5 @@
 from django.contrib import admin
-from .models import Notification
+from .models import Notification, Subscription
 
 admin.site.register(Notification)
+admin.site.register(Subscription)
diff --git a/djangoldp_notification/factories.py b/djangoldp_notification/factories.py
index 36329c4..1910325 100644
--- a/djangoldp_notification/factories.py
+++ b/djangoldp_notification/factories.py
@@ -10,7 +10,7 @@ class NotificationFactory(factory.django.DjangoModelFactory):
 
     type = factory.Faker('text', max_nb_chars=50)
     summary = factory.Faker('paragraph', nb_sentences=3, variable_nb_sentences=True)
-    author_user = factory.Iterator(User.objects.all())
+    author_user = factory.Faker('url')
     user = factory.Iterator(User.objects.all())
     date = factory.Faker('past_datetime')
     read = factory.Faker('boolean')
diff --git a/djangoldp_notification/migrations/0001_initial.py b/djangoldp_notification/migrations/0001_initial.py
index fe8bccd..b782358 100644
--- a/djangoldp_notification/migrations/0001_initial.py
+++ b/djangoldp_notification/migrations/0001_initial.py
@@ -1,5 +1,5 @@
 # -*- coding: utf-8 -*-
-# Generated by Django 1.11 on 2019-01-11 08:04
+# Generated by Django 1.11 on 2019-01-15 10:40
 from __future__ import unicode_literals
 
 from django.conf import settings
@@ -20,17 +20,28 @@ class Migration(migrations.Migration):
             name='Notification',
             fields=[
                 ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+                ('author_user', models.URLField()),
                 ('object', models.URLField()),
                 ('type', models.CharField(max_length=255)),
                 ('summary', models.TextField()),
                 ('date', models.DateTimeField(auto_now_add=True)),
                 ('read', models.BooleanField()),
-                ('author_user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='notifications_sent', to=settings.AUTH_USER_MODEL)),
-                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='notifications_received', to=settings.AUTH_USER_MODEL)),
+                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='inbox', to=settings.AUTH_USER_MODEL)),
             ],
             options={
                 'ordering': ['date'],
                 'permissions': (('view_notification', 'Read'), ('control_notification', 'Control')),
             },
         ),
+        migrations.CreateModel(
+            name='Subscription',
+            fields=[
+                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+                ('object', models.URLField()),
+                ('inbox', models.URLField()),
+            ],
+            options={
+                'permissions': (('view_notification', 'Read'), ('control_notification', 'Control')),
+            },
+        ),
     ]
diff --git a/djangoldp_notification/models.py b/djangoldp_notification/models.py
index 266c2a7..1de2593 100644
--- a/djangoldp_notification/models.py
+++ b/djangoldp_notification/models.py
@@ -1,23 +1,62 @@
+# import requests
+# import logging
+# import datetime
+# from threading import Thread
 from django.db import models
 from django.conf import settings
+from django.db.models.signals import post_save
+from django.dispatch import receiver
 from django.contrib.auth.models import User
+from django.contrib.admin.models import LogEntry
 
 class Notification(models.Model):
-    user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='notifications_received')
-    author_user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='notifications_sent')
+    user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='inbox')
+    author_user = models.URLField()
     object = models.URLField()
     type = models.CharField(max_length=255)
     summary = models.TextField()
     date = models.DateTimeField(auto_now_add=True)
     read = models.BooleanField()
     class Meta:
-        rdf_type = 'sib:source'
         permissions = (
             ('view_notification', 'Read'),
             ('control_notification', 'Control'),
         )
-        auto_author = 'author_user'
         ordering = ['date']
 
     def __str__(self):
         return '{}'.format(self.type)
+
+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 ---
+# @receiver(post_save, dispatch_uid="callback_notif")
+# def send_notification(sender, instance, **kwargs):
+#     if (sender != Notification and sender != LogEntry):
+#         threads = []
+#         url = sender.url # TODO : get URL of saved resource
+#         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
\ No newline at end of file
diff --git a/djangoldp_notification/settings.py b/djangoldp_notification/settings.py
new file mode 100644
index 0000000..3428c3a
--- /dev/null
+++ b/djangoldp_notification/settings.py
@@ -0,0 +1 @@
+USER_NESTED_FIELDS = ['inbox']
\ No newline at end of file
diff --git a/djangoldp_notification/urls.py b/djangoldp_notification/urls.py
index bc15376..cf9f127 100644
--- a/djangoldp_notification/urls.py
+++ b/djangoldp_notification/urls.py
@@ -1,9 +1,10 @@
 """djangoldp_notifications URL Configuration"""
 from django.conf.urls import url
-from .models import Notification
+from .models import Notification, Subscription
 from djangoldp.views import LDPViewSet
-
+#from djangoldp.permissions import InboxPermissions
 
 urlpatterns = [
-    url(r'^notifications/', LDPViewSet.urls(model=Notification)),
+    url(r'^notifications/', LDPViewSet.urls(model=Notification)),# permissions_classes=(InboxPermissions,),)),
+    url(r'^subscriptions/', LDPViewSet.urls(model=Subscription)),
 ]
-- 
GitLab