From 0d0166699600f8fa0ca3bbb90f4241db8bcc4df2 Mon Sep 17 00:00:00 2001 From: Holger Trampe Date: Thu, 11 Jun 2020 11:15:58 +0200 Subject: [PATCH] PUSH allgemeiner umgebaut, Gruppenbenachrichtigungen fertig --- users/mainwebsocket.py | 27 +++++- users/signals.py | 152 ++++++++++++++++++-------------- users/templates/users/base.html | 9 +- users/views.py | 10 +++ 4 files changed, 119 insertions(+), 79 deletions(-) diff --git a/users/mainwebsocket.py b/users/mainwebsocket.py index 21cfa07..aa843ab 100644 --- a/users/mainwebsocket.py +++ b/users/mainwebsocket.py @@ -31,9 +31,12 @@ class UsersConsumer(WebsocketConsumer): self.appconnect = True else: loggeduser = self.scope["user"] - + # Jemand neues kommt online, daher einmal die Presence updaten Presence.objects.touch(self.channel_name) - Room.objects.add("agency_" + str(loggeduser.profile.agency.pk), self.channel_name, loggeduser) + + # Nutzer in Agenturraum und eigenen Raum hinzufügen + 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): if(not self.appconnect): @@ -44,7 +47,8 @@ class UsersConsumer(WebsocketConsumer): pathcheck = self.scope["path"].split("/") loggeduser = User.objects.get(pk=Token.objects.get(key=pathcheck[5]).user_id) 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) @@ -68,9 +72,17 @@ class UsersConsumer(WebsocketConsumer): def update_standard(self, event): 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 def agency_newnews(self, event): - print(event["pushtext"]) self.send("pushnotification__news__" + event["pushtext"]) #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"]) 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) def disconnect(self, close_code): @@ -148,6 +161,9 @@ class UsersChat(WebsocketConsumer): def agency_newnews(self, event): self.send("Neue Agenturnews!") + def pushhandler(self, event): + self.send(event["pushtext"]) + # SOMETHING IN PRESENCE CHANGED def update_presence_live(self, event): self.send("presence_update") @@ -217,6 +233,9 @@ class GroupChat(WebsocketConsumer): def agency_newnews(self, event): self.send("Neue Agenturnews!") + def pushhandler(self, event): + self.send(event["pushtext"]) + # SOMETHING IN PRESENCE CHANGED def update_presence_live(self, event): self.send("presence_update") diff --git a/users/signals.py b/users/signals.py index cb9c910..accd667 100644 --- a/users/signals.py +++ b/users/signals.py @@ -108,28 +108,25 @@ def checkDefaultAbsenceReasons(sender, user, request, **kwargs): for u in uina: UserYearAbsenceInfo(agency=user.profile.agency, user=u, year=today.year+2).save() + +''' + FUNKTION ZUM SENDEN VON MAILS AUS EINEM SIGNAL + +''' +def sendMailNoti(notificationtext, user_touched): + + username = user_touched.first_name + " " + user_touched.last_name + msg_html = render_to_string('notificsys/notification_mail.html', {'username': username, 'notificationtext' : notificationtext}) + send_mail( + '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 + ) - ''' - class UserYearAbsenceInfo(models.Model): - agency = models.ForeignKey(Agency, on_delete=models.PROTECT, default=None) - user = models.ForeignKey(User, on_delete=models.CASCADE) - year = models.IntegerField() - days = models.FloatField(default=24.0) - restdays = models.FloatField(default=0.0) - ''' - - ''' - 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 @receiver(pre_delete, sender=News) @@ -137,70 +134,90 @@ def del_news_notifications(sender, instance, **kwargs): UserNotification.objects.filter(elementid=instance.pk).delete() -# SIGNALS FOR USER -''' -@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() -''' +#USER SIGNAL @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() - + # 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) 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): group_touched = AgencyGroup.objects.get(group=instance) userid = list(pk_set)[0] user_touched = User.objects.get(pk=userid) - - # PUSH NOTIFICATION FOR GROUOPCHANGES - if(user_touched.profile.add_new_group_push): + # PUSH NOTIFICATION FOR GROUOPCHANGES AND WEBSOCKET + if(user_touched.usernotifications.group_activity_push): if(action == 'post_remove'): newnotification = UserNotification(touser=user_touched, notificationtext="Sie wurden aus der Gruppe " + group_touched.agencygroupname + " entfernt.", notificationtype="groupchanges") 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 elif(action == 'post_add'): + newnotification = UserNotification(touser=user_touched, notificationtext="Sie wurden zur Gruppe " + group_touched.agencygroupname + " hinzugefügt.", notificationtype="groupchanges") 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 - if(user_touched.profile.add_new_group_mail): + if(user_touched.usernotifications.group_activity_mail): notificationtext = "" if(action == 'post_remove'): + notificationtext = "Sie wurden aus der Gruppe " + group_touched.agencygroupname + " entfernt." username = user_touched.first_name + " " + user_touched.last_name msg_html = render_to_string('notificsys/notification_mail.html', {'username': username, 'notificationtext' : notificationtext}) - if(GLOBALSENDMAILS): - send_mail( - '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 - ) + send_mail( + '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 + ) # A USER WAS ADDED TO A GROUP 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 msg_html = render_to_string('notificsys/notification_mail.html', {'username': username, 'notificationtext' : notificationtext}) - if(GLOBALSENDMAILS): - send_mail( - '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 - ) + send_mail( + '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 + ) # SIGNAL FOR STANDARDS POST SAVE diff --git a/users/templates/users/base.html b/users/templates/users/base.html index 423e892..f2d8273 100644 --- a/users/templates/users/base.html +++ b/users/templates/users/base.html @@ -717,16 +717,11 @@ $(document).ready(function(){ //HANDLER FOR ALL PUSHNOTIFICATIONS 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', { - body: e["data"].split("__")[2] + body: e["data"].split("__")[1] }); - } - {% endif %} - } loadUnsendNotifications(); loadUnviewnNotifications(); diff --git a/users/views.py b/users/views.py index 898ba2d..449362e 100644 --- a/users/views.py +++ b/users/views.py @@ -44,6 +44,9 @@ from datetime import date from timemanagement.models import Workday import base64 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): """Generate a random string of fixed length """ @@ -102,12 +105,16 @@ def toUpdate(request): print("default groups existing") # 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] perms = AgencyGroup._meta.permissions for p in perms: tempperm = Permission.objects.get(codename=p[0]) ag_admingroup.group.permissions.add(tempperm) + + # INITIAL ROOT DIR 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="agencynetwork")) + + m2m_changed.connect(adjust_group_notifications_permission, sender=Group.permissions.through) + # USER TIME MODEL usersofagency = User.objects.filter(profile__agency=request.user.profile.agency)