PUSH allgemeiner umgebaut, Gruppenbenachrichtigungen fertig

This commit is contained in:
Holger Trampe 2020-06-11 11:15:58 +02:00
parent 01bbe120b2
commit 0d01666996
4 changed files with 119 additions and 79 deletions

View File

@ -31,9 +31,12 @@ class UsersConsumer(WebsocketConsumer):
self.appconnect = True self.appconnect = True
else: else:
loggeduser = self.scope["user"] loggeduser = self.scope["user"]
# Jemand neues kommt online, daher einmal die Presence updaten
Presence.objects.touch(self.channel_name) Presence.objects.touch(self.channel_name)
# Nutzer in Agenturraum und eigenen Raum hinzufügen
Room.objects.add("agency_" + str(loggeduser.profile.agency.pk), self.channel_name, loggeduser) Room.objects.add("agency_" + str(loggeduser.profile.agency.pk), self.channel_name, loggeduser)
Room.objects.add("user_" + str(loggeduser.pk), self.channel_name, loggeduser)
def disconnect(self, close_code): def disconnect(self, close_code):
if(not self.appconnect): if(not self.appconnect):
@ -45,6 +48,7 @@ class UsersConsumer(WebsocketConsumer):
loggeduser = User.objects.get(pk=Token.objects.get(key=pathcheck[5]).user_id) loggeduser = User.objects.get(pk=Token.objects.get(key=pathcheck[5]).user_id)
loggeduser = self.scope["user"] loggeduser = self.scope["user"]
Room.objects.remove("agency_" + str(loggeduser.profile.agency.pk), self.channel_name) Room.objects.remove("agency_" + str(loggeduser.profile.agency.pk), self.channel_name)
Room.objects.remove("user_" + str(loggeduser.pk), self.channel_name, loggeduser)
Presence.objects.touch(self.channel_name) Presence.objects.touch(self.channel_name)
@ -68,9 +72,17 @@ class UsersConsumer(WebsocketConsumer):
def update_standard(self, event): def update_standard(self, event):
self.send("standard_update") self.send("standard_update")
'''
Generelle FUnktion zum Weiterleiten von PUSH-Nachrichten an den einzelnen User.
Die Infos werden dann in der Base.html zerlegt, die Nachrichten werden entweder in
der signals.py vorbereitet oder (im seltensten Fall) direkt bei der Datenveränderung.
'''
def pushhandler(self, event):
self.send(event["pushtext"])
# NEW AGENCY NEWS # NEW AGENCY NEWS
def agency_newnews(self, event): def agency_newnews(self, event):
print(event["pushtext"])
self.send("pushnotification__news__" + event["pushtext"]) self.send("pushnotification__news__" + event["pushtext"])
#self.send("Neue Agenturnews!") #self.send("Neue Agenturnews!")
@ -105,6 +117,7 @@ class UsersChat(WebsocketConsumer):
roomname = "privatechat_" + str(self.scope["url_route"]["kwargs"]["creator"]) + "_" + str(self.scope["url_route"]["kwargs"]["single"]) roomname = "privatechat_" + str(self.scope["url_route"]["kwargs"]["creator"]) + "_" + str(self.scope["url_route"]["kwargs"]["single"])
channel_layer = channels.layers.get_channel_layer() channel_layer = channels.layers.get_channel_layer()
Room.objects.add("user_" + str(loggeduser.pk), self.channel_name, loggeduser)
Room.objects.add(roomname, self.channel_name, loggeduser) Room.objects.add(roomname, self.channel_name, loggeduser)
def disconnect(self, close_code): def disconnect(self, close_code):
@ -148,6 +161,9 @@ class UsersChat(WebsocketConsumer):
def agency_newnews(self, event): def agency_newnews(self, event):
self.send("Neue Agenturnews!") self.send("Neue Agenturnews!")
def pushhandler(self, event):
self.send(event["pushtext"])
# SOMETHING IN PRESENCE CHANGED # SOMETHING IN PRESENCE CHANGED
def update_presence_live(self, event): def update_presence_live(self, event):
self.send("presence_update") self.send("presence_update")
@ -217,6 +233,9 @@ class GroupChat(WebsocketConsumer):
def agency_newnews(self, event): def agency_newnews(self, event):
self.send("Neue Agenturnews!") self.send("Neue Agenturnews!")
def pushhandler(self, event):
self.send(event["pushtext"])
# SOMETHING IN PRESENCE CHANGED # SOMETHING IN PRESENCE CHANGED
def update_presence_live(self, event): def update_presence_live(self, event):
self.send("presence_update") self.send("presence_update")

View File

@ -109,26 +109,23 @@ def checkDefaultAbsenceReasons(sender, user, request, **kwargs):
UserYearAbsenceInfo(agency=user.profile.agency, user=u, year=today.year+2).save() UserYearAbsenceInfo(agency=user.profile.agency, user=u, year=today.year+2).save()
'''
FUNKTION ZUM SENDEN VON MAILS AUS EINEM SIGNAL
''' '''
class UserYearAbsenceInfo(models.Model): def sendMailNoti(notificationtext, user_touched):
agency = models.ForeignKey(Agency, on_delete=models.PROTECT, default=None)
user = models.ForeignKey(User, on_delete=models.CASCADE) username = user_touched.first_name + " " + user_touched.last_name
year = models.IntegerField() msg_html = render_to_string('notificsys/notification_mail.html', {'username': username, 'notificationtext' : notificationtext})
days = models.FloatField(default=24.0) send_mail(
restdays = models.FloatField(default=0.0) 'Agentur-Benachrichtigung',
''' 'Hallo ' + user_touched.first_name + ' ' + user_touched.last_name + '! ' + notificationtext,
'noreply@digitale-agentur.com',
[user_touched.email],
html_message=msg_html,
fail_silently=True
)
'''
wd = Workday.objects.filter(user=user, end=None, start__day__lte=today.day)
for d in wd:
d.end = datetime.datetime(d.start.year, d.start.month, d.start.day, 23, 59, 00)
d.save()
for b in d.breaks.all():
if(b.end == None):
b.end = datetime.datetime(d.start.year, d.start.month, d.start.day, 23, 59, 00)
b.save()
'''
# Deletes all Notifications added to to delete news # Deletes all Notifications added to to delete news
@ -137,70 +134,90 @@ def del_news_notifications(sender, instance, **kwargs):
UserNotification.objects.filter(elementid=instance.pk).delete() UserNotification.objects.filter(elementid=instance.pk).delete()
# SIGNALS FOR USER #USER SIGNAL
'''
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
print(instance)
if created:
Profile.objects.create(user=instance, agency=instance.agency, parent=instance.parent)
#Wenn ein neuer Nutzer angelegt wird und dies der erste der Agentur ist,
#erhält dieser automatisch alle verfügbaren Rechte!
user_agency = User.objects.filter(profile__agency__pk=instance.agency.pk)
if len(user_agency) == 1:
tempuser = user_agency[0]
temprof = Profile
for ele in temprof._meta.permissions:
tempperm = Permission.objects.get(codename=ele[0])
tempuser.user_permissions.add(tempperm)
#tempuser.profile.func = 'lead'
tempuser.save()
'''
@receiver(post_save, sender=User) @receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs): def save_profile(sender, instance, **kwargs):
instance.profile.save() instance.profile.save()
# SIGNALS FOR GROUPS # SIGNALS FOR GROUPS
# Signal für das Ändern von Gruppenrechten
@receiver(signal=m2m_changed, sender=Group.permissions.through)
def adjust_group_notifications_permission(instance, action, reverse, model, pk_set, using, *args, **kwargs):
group_touched = AgencyGroup.objects.get(group=instance)
# Rechte wurden hinzugefügt
if(action == "post_add"):
users_in_group = instance.user_set.all()
for user in users_in_group:
if(user.usernotifications.group_rights_mail):
notificationtext = "Die Gruppe " + group_touched.agencygroupname + " hat neue Rechte erhalten."
sendMailNoti(notificationtext, user)
if(user.usernotifications.group_rights_push):
newnotification = UserNotification(touser=user, notificationtext="Die Gruppe " + group_touched.agencygroupname + " hat neue Rechte erhalten.", notificationtype="groupchanges")
newnotification.save()
channel_layer = channels.layers.get_channel_layer()
async_to_sync(channel_layer.group_send)("user_" + str(user.pk), {'type' : 'pushhandler', 'pushtext' : "pushnotification__Gruppenaktivität | Die Gruppe " + group_touched.agencygroupname + " hat neue Rechte erhalten."})
# Rechte wurden entfernt
elif(action == "post_remove"):
users_in_group = instance.user_set.all()
for user in users_in_group:
if(user.usernotifications.group_rights_mail):
notificationtext = "Der Gruppe " + group_touched.agencygroupname + " wurden Rechte entzogen."
sendMailNoti(notificationtext, user)
if(user.usernotifications.group_rights_push):
newnotification = UserNotification(touser=user, notificationtext="Der Gruppe " + group_touched.agencygroupname + " wurden Rechte entzogen.", notificationtype="groupchanges")
newnotification.save()
channel_layer = channels.layers.get_channel_layer()
async_to_sync(channel_layer.group_send)("user_" + str(user.pk), {'type' : 'pushhandler', 'pushtext' : "pushnotification__Gruppenaktivität | Der Gruppe " + group_touched.agencygroupname + " wurden Rechte entzogen."})
# Signal, wenn ein Nutzer aus der Gruppe entfernt/hinzugefügt wird
@receiver(signal=m2m_changed, sender=User.groups.through) @receiver(signal=m2m_changed, sender=User.groups.through)
def adjust_group_notifications(instance, action, reverse, model, pk_set, using, *args, **kwargs): def adjust_group_notifications(instance, action, reverse, model, pk_set, using, *args, **kwargs):
# IF FALSE NO MAILS WILL BE SEND - IN PRODUCTIVITY CHANGE TO TRUE #
GLOBALSENDMAILS = True
# GROUPSETTINGS FOR SOME USER WAS CHANGED
if isinstance(instance, Group): if isinstance(instance, Group):
group_touched = AgencyGroup.objects.get(group=instance) group_touched = AgencyGroup.objects.get(group=instance)
userid = list(pk_set)[0] userid = list(pk_set)[0]
user_touched = User.objects.get(pk=userid) user_touched = User.objects.get(pk=userid)
# PUSH NOTIFICATION FOR GROUOPCHANGES AND WEBSOCKET
# PUSH NOTIFICATION FOR GROUOPCHANGES if(user_touched.usernotifications.group_activity_push):
if(user_touched.profile.add_new_group_push):
if(action == 'post_remove'): if(action == 'post_remove'):
newnotification = UserNotification(touser=user_touched, notificationtext="Sie wurden aus der Gruppe " + group_touched.agencygroupname + " entfernt.", notificationtype="groupchanges") newnotification = UserNotification(touser=user_touched, notificationtext="Sie wurden aus der Gruppe " + group_touched.agencygroupname + " entfernt.", notificationtype="groupchanges")
newnotification.save() newnotification.save()
channel_layer = channels.layers.get_channel_layer()
async_to_sync(channel_layer.group_send)("user_" + str(user_touched.pk), {'type' : 'pushhandler', 'pushtext' : "pushnotification__Gruppenaktivität | Sie wurden aus der Gruppe " + group_touched.agencygroupname + " entfernt."})
# A USER WAS ADDED TO A GROUP # A USER WAS ADDED TO A GROUP
elif(action == 'post_add'): elif(action == 'post_add'):
newnotification = UserNotification(touser=user_touched, notificationtext="Sie wurden zur Gruppe " + group_touched.agencygroupname + " hinzugefügt.", notificationtype="groupchanges") newnotification = UserNotification(touser=user_touched, notificationtext="Sie wurden zur Gruppe " + group_touched.agencygroupname + " hinzugefügt.", notificationtype="groupchanges")
newnotification.save() newnotification.save()
channel_layer = channels.layers.get_channel_layer()
async_to_sync(channel_layer.group_send)("user_" + str(user_touched.pk), {'type' : 'pushhandler', 'pushtext' : "pushnotification__Gruppenaktivität | Sie wurden zur Gruppe " + group_touched.agencygroupname + " hinzugefügt."})
# E-MAILNOTIFICATIONS FOR GROUPCHANGES # E-MAILNOTIFICATIONS FOR GROUPCHANGES
if(user_touched.profile.add_new_group_mail): if(user_touched.usernotifications.group_activity_mail):
notificationtext = "" notificationtext = ""
if(action == 'post_remove'): if(action == 'post_remove'):
notificationtext = "Sie wurden aus der Gruppe " + group_touched.agencygroupname + " entfernt." notificationtext = "Sie wurden aus der Gruppe " + group_touched.agencygroupname + " entfernt."
username = user_touched.first_name + " " + user_touched.last_name username = user_touched.first_name + " " + user_touched.last_name
msg_html = render_to_string('notificsys/notification_mail.html', {'username': username, 'notificationtext' : notificationtext}) msg_html = render_to_string('notificsys/notification_mail.html', {'username': username, 'notificationtext' : notificationtext})
if(GLOBALSENDMAILS): send_mail(
send_mail( 'Agentur-Benachrichtigung',
'Agentur-Benachrichtigung', 'Hallo ' + user_touched.first_name + ' ' + user_touched.last_name + '! ' + notificationtext,
'Hallo ' + user_touched.first_name + ' ' + user_touched.last_name + '! ' + notificationtext, 'noreply@digitale-agentur.com',
'noreply@digitale-agentur.com', [user_touched.email],
[user_touched.email], html_message=msg_html,
html_message=msg_html, fail_silently=True
fail_silently=True )
)
# A USER WAS ADDED TO A GROUP # A USER WAS ADDED TO A GROUP
elif(action == 'post_add'): elif(action == 'post_add'):
@ -208,15 +225,14 @@ def adjust_group_notifications(instance, action, reverse, model, pk_set, using,
username = user_touched.first_name + " " + user_touched.last_name username = user_touched.first_name + " " + user_touched.last_name
msg_html = render_to_string('notificsys/notification_mail.html', {'username': username, 'notificationtext' : notificationtext}) msg_html = render_to_string('notificsys/notification_mail.html', {'username': username, 'notificationtext' : notificationtext})
if(GLOBALSENDMAILS): send_mail(
send_mail( 'Agentur-Benachrichtigung',
'Agentur-Benachrichtigung', 'Hallo ' + user_touched.first_name + ' ' + user_touched.last_name + '! ' + notificationtext,
'Hallo ' + user_touched.first_name + ' ' + user_touched.last_name + '! ' + notificationtext, 'noreply@digitale-agentur.com',
'noreply@digitale-agentur.com', [user_touched.email],
[user_touched.email], html_message=msg_html,
html_message=msg_html, fail_silently=True
fail_silently=True )
)
# SIGNAL FOR STANDARDS POST SAVE # SIGNAL FOR STANDARDS POST SAVE

View File

@ -717,16 +717,11 @@ $(document).ready(function(){
//HANDLER FOR ALL PUSHNOTIFICATIONS //HANDLER FOR ALL PUSHNOTIFICATIONS
if(e["data"].split("__")[0] == "pushnotification"){ if(e["data"].split("__")[0] == "pushnotification"){
console.log(e["data"].split("__"))
{% if user.profile.news_push %}
// USER WANTS TO SEE NEWS PUSH
if(e["data"].split("__")[1] == "news"){
var notify = new Notification('Digitale Agentur', { var notify = new Notification('Digitale Agentur', {
body: e["data"].split("__")[2] body: e["data"].split("__")[1]
}); });
}
{% endif %}
} }
loadUnsendNotifications(); loadUnsendNotifications();
loadUnviewnNotifications(); loadUnviewnNotifications();

View File

@ -44,6 +44,9 @@ from datetime import date
from timemanagement.models import Workday from timemanagement.models import Workday
import base64 import base64
import filetype import filetype
from django.db.models.signals import m2m_changed
from django.contrib.auth.models import User, Group
from users.signals import adjust_group_notifications_permission
def randomString(stringLength=10): def randomString(stringLength=10):
"""Generate a random string of fixed length """ """Generate a random string of fixed length """
@ -102,12 +105,16 @@ def toUpdate(request):
print("default groups existing") print("default groups existing")
# CHECK FOR ALL POSSIBLE RIGHTS ON ADMINGROUP # CHECK FOR ALL POSSIBLE RIGHTS ON ADMINGROUP
m2m_changed.disconnect(adjust_group_notifications_permission, sender=Group.permissions.through)
ag_admingroup = list(AgencyGroup.objects.filter(agency=request.user.profile.agency, is_admin=True))[0] ag_admingroup = list(AgencyGroup.objects.filter(agency=request.user.profile.agency, is_admin=True))[0]
perms = AgencyGroup._meta.permissions perms = AgencyGroup._meta.permissions
for p in perms: for p in perms:
tempperm = Permission.objects.get(codename=p[0]) tempperm = Permission.objects.get(codename=p[0])
ag_admingroup.group.permissions.add(tempperm) ag_admingroup.group.permissions.add(tempperm)
# INITIAL ROOT DIR # INITIAL ROOT DIR
rootdir = DataDir.objects.filter(is_root=True, agency__pk=request.user.profile.agency.pk) rootdir = DataDir.objects.filter(is_root=True, agency__pk=request.user.profile.agency.pk)
@ -147,6 +154,9 @@ def toUpdate(request):
a.group.permissions.add(Permission.objects.get(codename="moduleorganizer")) a.group.permissions.add(Permission.objects.get(codename="moduleorganizer"))
a.group.permissions.add(Permission.objects.get(codename="agencynetwork")) a.group.permissions.add(Permission.objects.get(codename="agencynetwork"))
m2m_changed.connect(adjust_group_notifications_permission, sender=Group.permissions.through)
# USER TIME MODEL # USER TIME MODEL
usersofagency = User.objects.filter(profile__agency=request.user.profile.agency) usersofagency = User.objects.filter(profile__agency=request.user.profile.agency)