Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • djangoldp-packages/djangoldp-notification
  • decentral1se/djangoldp-notification
  • femmefaytale/djangoldp-notification
  • 3wc/djangoldp-notification
4 results
Show changes
Commits on Source (115)
Showing
with 482 additions and 96 deletions
......@@ -3,4 +3,7 @@ db.sqlite3
*.pyc
*.egg-info
dist
script
\ No newline at end of file
script
.idea/*
*/.idea/*
*.DS_STORE
---
image: python:3.6
image: python:3.11
stages:
- test
- release
include:
project: infra/gitlab
ref: master
file: templates/python.ci.yml
variables:
SIB_PROJECT_NAME: "sib_test"
SIB_PROJECT_DIR: "/builds/$SIB_PROJECT_NAME"
DJANGO_SETTINGS_MODULE: "$SIB_PROJECT_NAME.settings"
SIB_PACKAGE_CONTENT: >
{
"ldppackages": {
"djangoldp_project": "djangoldp_project",
"djangoldp_circle": "djangoldp_circle",
"djangoldp_notification": "djangoldp_notification",
"djangoldp_account": "djangoldp_account",
"djangoldp_skill": "djangoldp_skill",
"djangoldp_joboffer": "djangoldp_joboffer",
"djangoldp_conversation": "djangoldp_conversation",
"djangoldp_profile": "djangoldp_profile",
"oidc_provider": "git+https://github.com/jblemee/django-oidc-provider.git@develop"
},
"server": {
"site_url": "http://localhost:8000",
"allowed_hosts": [
],
"db_host": "localhost",
"db_name": "database",
"db_user": "me",
"db_pass": "changeit",
"smtp_host": "locahost",
"smtp_user": "user",
"smtp_pass": "changeit",
"admin_email": "admin@example.org",
"admin_name": "admin",
"admin_pass": "admin"
}
}
test:
stage: test
before_script:
- export PATH="$PATH:/root/.local/bin" PYTHONPATH="$SIB_PROJECT_DIR"
- pip install git+https://git.happy-dev.fr/startinblox/devops/sib.git
- cd /builds && DJANGO_SETTINGS_MODULE="" sib startproject $SIB_PROJECT_NAME
- echo $SIB_PACKAGE_CONTENT > $SIB_PROJECT_DIR/packages.yml
- cd $SIB_PROJECT_DIR
- sib install $SIB_PROJECT_NAME
- cd $CI_PROJECT_DIR
- pip install -e .[dev]
script:
- pytest
- pip install .[dev]
- python -m unittest djangoldp_notification.tests.runner
except:
- master
- tags
tags:
- test
publish:
stage: release
before_script:
- pip install python-semantic-release sib-commit-parser
- git config user.name "${GITLAB_USER_NAME}"
- git config user.email "${GITLAB_USER_EMAIL}"
- git remote set-url origin "https://gitlab-ci-token:${GL_TOKEN}@${CI_SERVER_HOST}/${CI_PROJECT_PATH}.git"
script:
- semantic-release publish
only:
- master
tags:
- deploy
cache: []
extends: .publish_pypi
recursive-include djangoldp_notification/templates *
\ No newline at end of file
graft djangoldp_notification
global‐exclude *.py[cod] __pycache__ *.so
\ No newline at end of file
......@@ -31,20 +31,26 @@ An object allowing a User to be notified of any change on a resource or a contai
| -------- | ---------- | ------- | ------------------------------------------------------------ |
| `object` | `URLField` | | ID of the resource or the container to watch |
| `inbox` | `URLField` | | ID of the inbox to notify when the resource or the container change |
| `field` | `CharField` | | (optional) if set, then object['field'] will be sent in the notification, not object |
| `disable_automatic_notifications` | `BooleanField` | `False` | By default, notifications will be sent to this inbox everytime the target object/container is updated. Setting this flag to true prevents this behaviour, meaning that notifications will have to be triggered manually |
For convenience, when you create a subscription on an object, DjangoLDP-Notification will parse the object for any one-to-many nested field relations. It will then create nested-subscriptions, i.e. a subscription on the nested field which sends an update to the same inbox, passing the parent model. If this behaviour is undesired you can delete the `Subscription` instance
You can automatically create required subscriptions based on your settings.py with this management command:
```bash
./manage.py create_subscriptions
```
# Middlewares
There is a `CurrentUserMiddleware` that catches the connected user of the last performed HTTP request and adds
to every model before it is saved. This is useful if you need to get the connected user that performed
the last HTTP request in a `pre_saved` signal. You can get it by using the following line :
There is a `CurrentUserMiddleware` that catches the connected user of the current HTTP request and makes it available through the `get_current_user` function :
```python
getattr(instance, MODEL_MODIFICATION_USER_FIELD, "Unknown user")
from djangoldp_notification.middlewares import get_current_user
get_current_user()
```
`MODEL_MODIFICATION_USER_FIELD` is a constant that lies in `djangoldp_notification.middlewares` and
`instance` is the instance of your model before save in DB.
# Signals
## Create notification on subscribed objects
......@@ -101,3 +107,26 @@ python3 manage.py mock_notification --older 10d
# Default. Will delete notifications older than 10 hours ago
python3 manage.py mock_notification --older 10h
```
## Check your datas integrity
Because of the way the DjangoLDP's federation work, you may want to send your notification to every subscribers sometimes.
Follow the [check_integrity](https://git.startinblox.com/djangoldp-packages/djangoldp#check-your-datas-integrity) command of DjangoLDP to get how much resources will be impacted:
```bash
./manage.py check_integrity
```
Then run this command to send notifications:
```bash
./manage.py check_integrity --send-subscription-notifications
```
Notice that you may have to restart your ActivityQueue or your DjangoLDP server, depending on [how you configured the ActivityQueueService](https://git.startinblox.com/djangoldp-packages/djangoldp/blob/master/djangoldp/conf/server_template/server/wsgi.py-tpl#L21-24)
## Changelog
Now supports Django4.2 and Python3.11
from django.contrib import admin
from djangoldp.admin import DjangoLDPAdmin
from djangoldp.models import Model
from .models import Notification, NotificationSetting, Subscription
@admin.register(Notification)
class NotificationAdmin(DjangoLDPAdmin):
list_display = ('urlid', 'user', 'author', 'type', 'object', 'unread')
exclude = ('urlid', 'is_backlink', 'allow_create_backlink')
search_fields = ['urlid', 'user__urlid', 'author', 'object', 'type', 'summary']
ordering = ['-urlid']
def get_queryset(self, request):
# Hide distant notification
queryset = super(NotificationAdmin, self).get_queryset(request)
internal_ids = [x.pk for x in queryset if not Model.is_external(x)]
return queryset.filter(pk__in=internal_ids)
@admin.register(Subscription)
class SubscriptionAdmin(DjangoLDPAdmin):
list_display = ('urlid', 'object', 'inbox', 'field')
exclude = ('urlid', 'is_backlink', 'allow_create_backlink')
search_fields = ['urlid', 'object', 'inbox', 'field']
ordering = ['urlid']
@admin.register(NotificationSetting)
class NotificationSettingAdmin(DjangoLDPAdmin):
list_display = ('urlid', 'user', 'receiveMail')
exclude = ('urlid', 'is_backlink', 'allow_create_backlink')
search_fields = ['urlid', 'user', 'receiveMail']
ordering = ['urlid']
from django.apps import apps
from django.conf import settings
from django.db import models
from djangoldp.models import Model
from djangoldp_notification.models import send_request, Subscription
class technical_user:
urlid = settings.BASE_URL
def add_arguments(parser):
parser.add_argument(
"--ignore-subscriptions",
default=False,
nargs="?",
const=True,
help="Ignore subscriptions related check",
)
parser.add_argument(
"--send-subscription-notifications",
default=False,
nargs="?",
const=True,
help="Send an update notification for every local resources to every subscribers",
)
def check_integrity(options):
print('---')
print("DjangoLDP Notification")
if(not options["ignore_subscriptions"]):
models_list = apps.get_models()
resources = set()
resources_map = dict()
for model in models_list:
for obj in model.objects.all():
if hasattr(obj, "urlid"):
if(obj.urlid):
if(obj.urlid.startswith(settings.BASE_URL)):
if(type(obj).__name__ != "ScheduledActivity" and type(obj).__name__ != "LogEntry" and type(obj).__name__ != "Activity"):
resources.add(obj.urlid)
resources_map[obj.urlid] = obj
print("Found "+str(len(resources_map))+" local resources on "+str(len(models_list))+" models for "+str(Subscription.objects.count())+" subscribers")
if(options["send_subscription_notifications"]):
sent=0
for resource in sorted(resources):
resource = resources_map[resource]
recipients = []
try:
url_container = settings.BASE_URL + Model.container_id(resource)
url_resource = settings.BASE_URL + Model.resource_id(resource)
except NoReverseMatch:
continue
for subscription in Subscription.objects.filter(models.Q(object=url_resource) | models.Q(object=url_container)):
if subscription.inbox not in recipients and not subscription.is_backlink:
# I may have configured to send the subscription to a foreign key
if subscription.field is not None and len(subscription.field) > 1:
try:
resource = getattr(resource, subscription.field, resource)
# don't send notifications for foreign resources
if hasattr(resource, 'urlid') and Model.is_external(resource.urlid):
continue
url_resource = settings.BASE_URL + Model.resource_id(resource)
except NoReverseMatch:
continue
except ObjectDoesNotExist:
continue
try:
send_request(subscription.inbox, url_resource, resource, False)
sent+=1
except:
print("Failed to create subscription activity for "+url_resource)
recipients.append(subscription.inbox)
print("Sent "+str(sent)+" activities to "+str(Subscription.objects.count())+" subscribers")
print("Depending on your server configuration, you may have to restart the ActivityQueue or the server to properly process em.")
else:
print("Send an update notification for all those resources to all of their subscribers with `./manage.py check_integrity --send-subscription-notifications`")
else:
print("Ignoring djangoldp-notification checks")
\ No newline at end of file
MIDDLEWARE = ['djangoldp_notification.middlewares.CurrentUserMiddleware']
\ No newline at end of file
File added
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <BENOIT@STARTINBLOX.COM>, 2022.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2022-04-19 21:34+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
#: models.py:206
msgid "Auteur inconnu"
msgstr "Unknown author"
#: models.py:263
msgid "Quelqu'un"
msgstr "Someone"
#: models.py:275
msgid "le chat"
msgstr "the chat"
#: models.py:278
msgid "t'a envoyé un message privé"
msgstr "sent you a private message"
#: models.py:280
msgid "t'a mentionné sur "
msgstr "mentioned you on "
#: models.py:295
msgid "Notification sur "
msgstr "Notification on "
#: templates/email.html:8
msgid "de"
msgstr "from"
#: templates/email.html:15
msgid "Ne réponds pas directement à cet e-mail, à la place rends-toi sur"
msgstr "Do not answer directly to this email, instead go to"
File added
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2022-04-19 21:34+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
#: models.py:206
msgid "Auteur inconnu"
msgstr ""
#: models.py:263
msgid "Quelqu'un"
msgstr ""
#: models.py:275
msgid "le chat"
msgstr ""
#: models.py:278
msgid "t'a envoyé un message privé"
msgstr ""
#: models.py:280
msgid "t'a mentionné sur "
msgstr ""
#: models.py:295
msgid "Notification sur "
msgstr ""
#: templates/email.html:8
msgid "de"
msgstr ""
#: templates/email.html:15
msgid "Ne réponds pas directement à cet e-mail, à la place rends-toi sur"
msgstr ""
File added
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2022-04-19 21:34+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"
#: models.py:206
msgid "Auteur inconnu"
msgstr "Auteur inconnu"
#: models.py:263
msgid "Quelqu'un"
msgstr "Quelqu'un"
#: models.py:275
msgid "le chat"
msgstr "le chat"
#: models.py:278
msgid "t'a envoyé un message privé"
msgstr "t'a envoyé un message privé"
#: models.py:280
msgid "t'a mentionné sur "
msgstr "t'a mentionné sur "
#: models.py:295
#, fuzzy
#| msgid "t'a mentionné sur "
msgid "Notification sur "
msgstr "t'a mentionné sur "
#: templates/email.html:8
msgid "de"
msgstr "de"
#: templates/email.html:15
msgid "Ne réponds pas directement à cet e-mail, à la place rends-toi sur"
msgstr "Ne réponds pas directement à cet e-mail, à la place rends-toi sur"
from django.core.management.base import BaseCommand
from django.conf import settings
from djangoldp_notification.models import Subscription
class Command(BaseCommand):
help = 'Create required subscriptions'
def handle(self, *args, **options):
host = getattr(settings, 'SITE_URL')
jabber_host = getattr(settings, 'JABBER_DEFAULT_HOST')
xmpp = getattr(settings, 'PROSODY_HTTP_URL')
try:
sub = Subscription.objects.get(object="{}/circles/".format(host))
sub.delete()
except Subscription.DoesNotExist:
pass
try:
sub = Subscription.objects.get(object="{}/projects/".format(host))
sub.delete()
except Subscription.DoesNotExist:
pass
try:
sub = Subscription.objects.get(object="{}/circle-members/".format(host))
sub.delete()
except Subscription.DoesNotExist:
pass
try:
sub = Subscription.objects.get(object="{}/project-members/".format(host))
sub.delete()
except Subscription.DoesNotExist:
pass
# Allow us to manage general information about circles and projects like name, jabberIDs, description, etc.
Subscription.objects.get_or_create(object=host+"/circles/", inbox=xmpp + "/conference." + jabber_host + "/startinblox_groups_muc_admin", field=None)
Subscription.objects.get_or_create(object=host+"/projects/", inbox=xmpp + "/conference." + jabber_host + "/startinblox_groups_muc_admin", field=None)
# The management of circle and projets members now comes from management of groups
Subscription.objects.get_or_create(object=host+"/groups/", inbox=xmpp + "/conference." + jabber_host + "/startinblox_groups_muc_members_admin", field=None)
# Allow us to manage general information about users, like their names, jabberID, avatars, etc.
Subscription.objects.get_or_create(object=host+"/users/", inbox=xmpp + "/" + jabber_host + "/startinblox_groups_user_admin", field=None)
# When we change an information about the user (like avatar and so on) we want to notify prosody
self.stdout.write(self.style.SUCCESS("Successfully created subscriptions\nhost: "+host+"\nxmpp server: "+xmpp+"\njabber host: "+jabber_host))
from textwrap import dedent
from datetime import datetime, timedelta
from django.utils import timezone
from django.core.management.base import BaseCommand, CommandError
from djangoldp_notification.models import Notification
......@@ -48,5 +49,5 @@ class Command(BaseCommand):
def handle(self, *args, **options):
older_than = _compute_time_limit(options["older"])
limit = datetime.today() - timedelta(minutes=older_than)
limit = timezone.now() - timedelta(minutes=older_than)
Notification.objects.filter(date__lte=limit).delete()
from django.db.models import signals
MODEL_MODIFICATION_USER_FIELD = 'modification_user'
from threading import local
_thread_locals = local()
class CurrentUserMiddleware:
def __init__(self, get_response=None):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
self.process_request(request)
response = self.get_response(request)
signals.pre_save.disconnect(dispatch_uid=request)
return response
def process_request(self, request):
if request.method in ('GET', 'HEAD', 'OPTION'):
# this request shouldn't update anything
# so no signal handler should be attached
return
if hasattr(request, 'user') and request.user.is_authenticated():
user = request.user
else:
user = None
def _update_users(sender, instance, **kwargs):
setattr(instance, MODEL_MODIFICATION_USER_FIELD, user)
_thread_locals._current_user = getattr(request, 'user', None)
return self.get_response(request)
signals.pre_save.connect(_update_users, dispatch_uid=request, weak=False)
def get_current_user():
return getattr(_thread_locals, '_current_user', None)
\ No newline at end of file
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2020-04-29 13:46
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('djangoldp_notification', '0002_auto_20190917_1107'),
]
operations = [
migrations.AddField(
model_name='notification',
name='allow_create_backlink',
field=models.BooleanField(default=True, help_text='set to False to disable backlink creation after Model save'),
),
migrations.AddField(
model_name='subscription',
name='allow_create_backlink',
field=models.BooleanField(default=True, help_text='set to False to disable backlink creation after Model save'),
),
]
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2020-05-01 12:07
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('djangoldp_notification', '0003_auto_20200429_1346'),
]
operations = [
migrations.AddField(
model_name='notification',
name='backlink_created',
field=models.BooleanField(default=False, help_text='set automatically to indicate the Model is a backlink'),
),
migrations.AddField(
model_name='subscription',
name='backlink_created',
field=models.BooleanField(default=False, help_text='set automatically to indicate the Model is a backlink'),
),
]
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2020-05-05 17:33
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('djangoldp_notification', '0004_auto_20200501_1207'),
]
operations = [
migrations.RenameField(
model_name='notification',
old_name='backlink_created',
new_name='is_backlink',
),
migrations.RenameField(
model_name='subscription',
old_name='backlink_created',
new_name='is_backlink',
),
]
# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2020-06-02 10:35
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('djangoldp_notification', '0005_auto_20200505_1733'),
]
operations = [
migrations.AddField(
model_name='subscription',
name='parent',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='children', to='djangoldp_notification.Subscription'),
),
]