from os import SEEK_CUR from django.shortcuts import render, redirect from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.models import User from django.views.generic import CreateView, ListView, UpdateView, DetailView, DeleteView, View from .models import NCFile, Standards, StandardComments, StandardCommentRate from django.contrib import messages from django.http import HttpResponse, JsonResponse from .forms import StandardAddStandard, StandardAddStandardEditor, StandardUpdateStandard, StandardUpdateStandardEditor from django.contrib.auth.decorators import login_required from tasks.models import Tasks from areas.models import Areas from datetime import datetime from users.models import AgencyGroup, AgencyNetwork from cloud.models import DataFile, DataDir from django.contrib.auth.decorators import login_required import re from django.template import defaultfilters from organizer.models import QuickLinks, AGContacts, AGPassword import channels.layers from asgiref.sync import async_to_sync from django.template.loader import render_to_string from notificsys.models import UserNotification from django.core.mail import send_mail # ALLE STANDARDS EINER AGENTUR class StandardsManagement(LoginRequiredMixin, ListView): model = Standards # Adding active_link # Loading only user same agency # Change context and return for template-data def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # # Get all Users of the Same Agency as logged user areas = Areas.objects.filter(agency__pk=self.request.user.profile.agency.pk).order_by("areaorder") standards_of_user = Standards.objects.filter(agency__pk=self.request.user.profile.agency.pk, created_standard_by=self.request.user.pk) #standards_of_agency = Standards.objects.filter(agency__pk=self.request.user.profile.agency.pk, public=True) unpubstandards_of_user = Standards.objects.filter(agency__pk=self.request.user.profile.agency.pk, public=False) #tasks = Tasks.objects.filter(agency__pk=self.request.user.profile.agency.pk) standardcontent = [] for a in areas: standardcontent.append({"area" : a, "tasks" : []}) tasks_in_area = Tasks.objects.filter(agency__pk=self.request.user.profile.agency.pk, area__pk=a.pk).order_by("name") for t in tasks_in_area: standardcontent[len(standardcontent)-1]['tasks'].append({"task" : t, "standards" : Standards.objects.filter(agency__pk=self.request.user.profile.agency.pk, area__pk=a.pk, task = t.pk, area = a.pk, public=True).order_by("-created_standard_date")}) #context.update({'active_link' : 'standards', 'tasks': tasks, 'unpubstandards_of_user' : unpubstandards_of_user, 'standards_of_agency' : standards_of_agency, 'areas' : areas, 'standards_of_user' : standards_of_user, 'standardcontent' : standardcontent}) #agencynetworks = AgencyNetwork.objects.filter(creator_agency=self.request.user.profile.agency) | AgencyNetwork.objects.filter(adminagencys__in=[self.request.user.profile.agency.pk]) | AgencyNetwork.objects.filter(members__in=[self.request.user.profile.agency.pk]) | AgencyNetwork.objects.filter(sharemembers__in=[self.request.user.profile.agency.pk]) #agencynetworks = AgencyNetwork.objects.filter(adminagencys__in=[self.request.user.profile.agency.pk]) | AgencyNetwork.objects.filter(members__in=[self.request.user.profile.agency.pk]) | AgencyNetwork.objects.filter(sharemembers__in=[self.request.user.profile.agency.pk]) agencynetworks_all = AgencyNetwork.objects.all() agencynetworks = [] for a in agencynetworks_all: if self.request.user.profile.agency in a.adminagencys.all() or self.request.user.profile.agency in a.members.all() or self.request.user.profile.agency in a.sharemembers.all(): agencynetworks.append(a) allagencynetworkstandards = [] for agn in agencynetworks: for agn_s in agn.standards.all(): allagencynetworkstandards.append(agn_s) allagencynetworkstandards.sort(key=lambda x: x.agencynetworkcounter, reverse=True) # Beliebte Standards famestandards = [] famecounter = 0 for s in allagencynetworkstandards: if famecounter < 10 and s not in famestandards: famestandards.append(s) famecounter += 1 context.update({'active_link' : 'standards', 'unpubstandards_of_user' : unpubstandards_of_user, 'areas' : areas, 'standards_of_user' : standards_of_user, 'standardcontent' : standardcontent, "agencynetworks" : agencynetworks, "allagencynetworkstandards" : allagencynetworkstandards, 'famestandards' : famestandards}) return context @login_required def getFileFromStandard(request, nc_id): print(nc_id) return JsonResponse({}) @login_required def checkUserDirRights(request, startdir, userid): canview = True user = User.objects.get(pk=userid) usergroups=list(user.groups.all()) grouptomach = [] singleObj = DataDir.objects.get(pk=startdir.pk) # AGENCYCHECK if(singleObj.agency.pk == user.profile.agency.pk): # Get dirs to check while( singleObj.is_root != True and canview == True): for g in singleObj.visibleby.all(): grouptomach.append(g.group) if(len(grouptomach) == 0): canview = True else: if(len(set(usergroups).intersection(grouptomach)) > 0): canview = True else: canview = False grouptomach = [] singleObj = DataDir.objects.get(pk=singleObj.parent.pk) else: canview = False return canview # NEW FOR NC import requests from django.conf import settings from digitaleagentur.utils import * @login_required def StandardAdd(request, id=False): # NEW STANDARD if(id == False): if request.method == 'POST': normalForm = StandardAddStandard(request.POST, instance=request.user) editorForm = StandardAddStandardEditor(request.POST, instance=request.user) if editorForm.is_valid() and normalForm.is_valid(): normalForm.agency = request.user.profile.agency normalForm.created_standard_by = request.user normalForm.created_standard_date = datetime.now() normalForm.published_by = request.user normalForm.last_modifed_by = request.user normalForm.save() editorForm.save() new_standard = Standards() new_standard.agency = request.user.profile.agency new_standard.created_standard_by = request.user new_standard.published_by = request.user new_standard.last_modified_by = request.user new_standard.created_standard_date = datetime.now() new_standard.last_modified_on = datetime.now() new_standard.task = normalForm.cleaned_data['task'] new_standard.area = normalForm.cleaned_data['area'] new_standard.name = normalForm.cleaned_data['name'] new_standard.content = editorForm.cleaned_data['content'] new_standard.public = normalForm.cleaned_data['public'] new_standard.freefield_content = normalForm.cleaned_data['freefield_content'] new_standard.freefield_title = normalForm.cleaned_data['freefield_title'] new_standard.save() #new_standard.representative.set(normalForm.cleaned_data['representative']) #new_standard.executor.set(normalForm.cleaned_data['executor']) #new_standard.authority.set(normalForm.cleaned_data['authority']) # USERS # REPRESENTATIV verant = normalForm.cleaned_data['us_verant'].split(",") for v in verant: if(v.isdigit()): new_standard.authority.add(User.objects.get(pk=v)) # EXECUTORS ex = normalForm.cleaned_data['us_ex'].split(",") for v in ex: if(v.isdigit()): new_standard.executor.add(User.objects.get(pk=v)) # AUTHORITY ver = normalForm.cleaned_data['us_ver'].split(",") for v in ver: if(v.isdigit()): new_standard.representative.add(User.objects.get(pk=v)) # GROUPS BEI PERSONEN # verant_group = normalForm.cleaned_data['group_verant'].split(",") for v in verant_group: if(v.isdigit()): new_standard.authority_group.add(AgencyGroup.objects.get(pk=v)) # EXECUTORS ex_group = normalForm.cleaned_data['group_ex'].split(",") for v in ex_group: if(v.isdigit()): new_standard.executor_group.add(AgencyGroup.objects.get(pk=v)) # AUTHORITY ver_group = normalForm.cleaned_data['group_ver'].split(",") for v in ver_group: if(v.isdigit()): new_standard.representative_group.add(AgencyGroup.objects.get(pk=v)) # ADD GROUPS groups = normalForm.cleaned_data['checked_groups'].split(",") for g in groups: if(g.isdigit()): new_standard.visibleby.add(AgencyGroup.objects.get(pk=g)) # ADD STANDARDS standards = normalForm.cleaned_data['added_standards'].split(",") for s in standards: if(s.isdigit()): new_standard.linked_standards.add(Standards.objects.get(pk=s)) # ADD FILES #files = normalForm.cleaned_data['added_files'].split(",") #for f in files: # if(f.isdigit()): # new_standard.addedfiles.add(DataFile.objects.get(pk=f)) # ADD FILES files = normalForm.cleaned_data['added_files'].split(",") for f in files: if(f.isdigit()): ncfile = NCFile.objects.filter(nc_id=f).first() # Wenn die NC-File in Django nicht existiert, dann neu erstellen und hinzufügen. Trifft für Dateien zu, die zwar in den Dateien waren, aber noch nicht in der NC! if(ncfile == None): new_nc_file = NCFile(nc_id=f, agency=new_standard.agency) new_nc_file.save() new_standard.addedfiles_nc.add(new_nc_file) else: new_standard.addedfiles_nc.add(ncfile) # ADD QUICKLINKS quicklinks = normalForm.cleaned_data['added_quicklinks'].split(",") for f in quicklinks: if(f.isdigit()): new_standard.addedquicklinks.add(QuickLinks.objects.get(pk=f)) # ADD PASSWORDS addedpasswords = normalForm.cleaned_data['added_passwords'].split(",") for f in addedpasswords: if(f.isdigit()): new_standard.addedpasswords.add(AGPassword.objects.get(pk=f)) # ADD CONTACTS contacts = normalForm.cleaned_data['added_contacts'].split(",") for f in contacts: if(f.isdigit()): new_standard.addedcontacts.add(AGContacts.objects.get(pk=f)) tempstandardname = normalForm.cleaned_data['name'] if(new_standard.public and request.user.has_perm('users.standardmanager')): messages.success(request, f'Standard {tempstandardname} hinzugefügt und veröffentlicht.') else: new_standard.public = False new_standard.save() messages.success(request, f'Standard {tempstandardname} hinzugefügt! Dieser muss noch veröffentlicht werden.') return redirect('standards') else: normalForm = StandardAddStandard(instance=request.user) editorForm = StandardAddStandardEditor(instance=request.user) possibleFilesByVisible = [] # NC FILE # Data for the new User if(request.user.is_authenticated and getNCLoggedUserBySession(request.user.profile.nc_sid)): data_nc = { "Depth" : 0 } nc_login_headers = {'Authorization' : 'Bearer ' + request.user.profile.nc_sid} r = requests.request("PROPFIND", settings.NEXTCLOUD_URL + "remote.php/dav/files/" + request.user.username + "/Agenturdaten_" + str(request.user.profile.agency.pk) + "/", headers=nc_login_headers, data=data_nc) print(r.text) #allfiles = DataFile.objects.filter(agency=request.user.profile.agency) #for f in allfiles: # actParent = DataDir.objects.get(pk=f.parent.pk) # if actParent.is_root: # possibleFilesByVisible.append(f) # else: # if(checkUserDirRights(request, actParent, request.user.pk)): # possibleFilesByVisible.append(f) possibleFilesByVisible = [] filesearchdata = '/files/' + request.user.username + '/Agenturdaten/infinity1' #filesearchdata = 'infinity' r = requests.request("SEARCH", settings.NEXTCLOUD_URL + "remote.php/dav/", data=filesearchdata, headers={'Content-Type' : 'text/xml', 'Authorization' : "Bearer " + request.user.profile.nc_sid}) # IDs filtern aus XML-Response try: split_response = r.text.split("") # Header des XML-Response entfernen split_response.pop(0) # IDs from the User for ele in split_response: new_id = ele.split("")[0] possibleFilesByVisible.append(new_id) except: pass context = { 'normalForm' : normalForm, 'editorForm' : editorForm, 'active_link' : 'standards', 'agencygroups' : AgencyGroup.objects.filter(agency=request.user.profile.agency), 'usersofagency' : User.objects.filter(profile__agency=request.user.profile.agency), 'files' : possibleFilesByVisible, #'parentid' : list(DataDir.objects.filter(agency=request.user.profile.agency, is_root=True))[0].pk, 'standards' : Standards.objects.filter(agency=request.user.profile.agency, public=True), 'quicklinks' : QuickLinks.objects.filter(agency=request.user.profile.agency), 'contacts' : AGContacts.objects.filter(agency=request.user.profile.agency), 'passwords' : AGPassword.objects.filter(agency=request.user.profile.agency), 'aggroups' : AgencyGroup.objects.filter(agency=request.user.profile.agency), } return render(request, 'standards/standards_add.html', context) # UPDATE A STANDARD else: standard = Standards.objects.get(pk=id, agency=request.user.profile.agency) # SAVE UPDATED STANDARD if request.method == 'POST': # CHECK IF USER HAS RIGHTS TO SEE THIS DIR groupsofstandard = standard userisingroup = False if len(groupsofstandard.visibleby.all()) == 0: userisingroup = True else: for ag in groupsofstandard.visibleby.all(): if ag.group in request.user.groups.all(): userisingroup = True if userisingroup: normalForm = StandardUpdateStandard(request.POST, instance=standard) editorForm = StandardUpdateStandardEditor(request.POST, instance=standard) if editorForm.is_valid() and normalForm.is_valid(): standard.last_modified_by = request.user standard.last_modified_on = datetime.now() standard.task = normalForm.cleaned_data['task'] standard.area = normalForm.cleaned_data['area'] standard.name = normalForm.cleaned_data['name'] standard.public = normalForm.cleaned_data['public'] standard.content = editorForm.cleaned_data['content'] standard.freefield_content = normalForm.cleaned_data['freefield_content'] standard.freefield_title = normalForm.cleaned_data['freefield_title'] # Clear Users, will set again next step standard.authority.clear() standard.executor.clear() standard.representative.clear() # GROUPS standard.authority_group.clear() standard.executor_group.clear() standard.representative_group.clear() standard.visibleby.clear() standard.linked_standards.clear() standard.addedfiles_nc.clear() standard.addedquicklinks.clear() standard.addedpasswords.clear() standard.addedcontacts.clear() # ADD NEW INFOS # REPRESENTATIV verant = normalForm.cleaned_data['us_verant'].split(",") for v in verant: if(v.isdigit()): standard.authority.add(User.objects.get(pk=v)) # EXECUTORS ex = normalForm.cleaned_data['us_ex'].split(",") for v in ex: if(v.isdigit()): standard.executor.add(User.objects.get(pk=v)) # AUTHORITY ver = normalForm.cleaned_data['us_ver'].split(",") for v in ver: if(v.isdigit()): standard.representative.add(User.objects.get(pk=v)) verant_group = normalForm.cleaned_data['group_verant'].split(",") for v in verant_group: if(v.isdigit()): standard.authority_group.add(AgencyGroup.objects.get(pk=v)) # EXECUTORS ex_group = normalForm.cleaned_data['group_ex'].split(",") for v in ex_group: if(v.isdigit()): standard.executor_group.add(AgencyGroup.objects.get(pk=v)) # AUTHORITY ver_group = normalForm.cleaned_data['group_ver'].split(",") for v in ver_group: if(v.isdigit()): standard.representative_group.add(AgencyGroup.objects.get(pk=v)) # ADD GROUPS groups = normalForm.cleaned_data['checked_groups'].split(",") for g in groups: if(g.isdigit()): standard.visibleby.add(AgencyGroup.objects.get(pk=g)) # ADD STANDARDS standards = normalForm.cleaned_data['added_standards'].split(",") for s in standards: if(s.isdigit()): standard.linked_standards.add(Standards.objects.get(pk=s)) # ADD FILES files = normalForm.cleaned_data['added_files'].split(",") for f in files: if(f.isdigit()): ncfile = NCFile.objects.filter(nc_id=f).first() # Wenn die NC-File in Django nicht existiert, dann neu erstellen und hinzufügen. Trifft für Dateien zu, die zwar in den Dateien waren, aber noch nicht in der NC! if(ncfile == None): new_nc_file = NCFile(nc_id=f, agency=standard.agency) new_nc_file.save() standard.addedfiles_nc.add(new_nc_file) else: standard.addedfiles_nc.add(ncfile) # ADD QUICKLINKS quicklinks = normalForm.cleaned_data['added_quicklinks'].split(",") for f in quicklinks: if(f.isdigit()): standard.addedquicklinks.add(QuickLinks.objects.get(pk=f)) # ADD PASSWORDS addedpasswords = normalForm.cleaned_data['added_passwords'].split(",") for f in addedpasswords: if(f.isdigit()): standard.addedpasswords.add(AGPassword.objects.get(pk=f)) # ADD CONTACTS contacts = normalForm.cleaned_data['added_contacts'].split(",") for f in contacts: if(f.isdigit()): standard.addedcontacts.add(AGContacts.objects.get(pk=f)) # ADD TO NETWORKS networks = normalForm.cleaned_data['checked_networks'].split(",") ''' Alle Agenturverbunde laden, in denen die Agentur drin ist. ''' agencynetworks_all = AgencyNetwork.objects.all() agencynetworks = [] for a in agencynetworks_all: if request.user.profile.agency in a.adminagencys.all() or request.user.profile.agency in a.members.all() or request.user.profile.agency in a.sharemembers.all(): agencynetworks.append(a) agencynetworks_standard_in = [] # Agenturverbünde, in denen der Standard drin sein soll for f in networks: if(f.isdigit()): tempnetwork = AgencyNetwork.objects.get(pk=f) #tempnetwork.standards.add(standard) agencynetworks_standard_in.append(tempnetwork) #print(agencynetworks_standard_in) # Wenn Standard im gewünschten Verbund, dann rein, ansonsten raus for a in agencynetworks: if a in agencynetworks_standard_in and standard not in a.standards.all(): a.standards.add(standard) elif a not in agencynetworks_standard_in: a.standards.remove(standard) ''' Info an die Agenturen über einen neuen Standard ''' agency_send = [] for agencynetwork_single in agencynetworks_standard_in: for agn_admin in agencynetwork_single.adminagencys.all(): if(agn_admin not in agency_send): agency_send.append(agn_admin) if agn_admin != request.user.profile.agency: users_of_other_ag = User.objects.filter(profile__agency=agn_admin) for u in users_of_other_ag: if u.has_perm('users.standardmanager') and u.has_perm('users.agencynetwork'): if u.usernotifications.agn_standard_created_mail: notificationtext = "im Agenturverbund " + agencynetwork_single.name + " wurde ein neuer Standard geteilt: " + standard.name sendMailNoti(notificationtext, u) if u.usernotifications.agn_standard_created_push: newnotification = UserNotification(touser=u, notificationtext="im Agenturverbund " + agencynetwork_single.name + " wurde ein neuer Standard geteilt: " + standard.name, notificationtype="") newnotification.save() channel_layer = channels.layers.get_channel_layer() async_to_sync(channel_layer.group_send)("user_" + str(u.pk), {'type' : 'pushhandler', 'pushtext' : "pushnotification__Agenturverbund | Im Agenturverbund " + agencynetwork_single.name + " wurde ein neuer Standard geteilt: " + standard.name}) for agn_admin in agencynetwork_single.members.all(): if(agn_admin not in agency_send): agency_send.append(agn_admin) if agn_admin != request.user.profile.agency: users_of_other_ag = User.objects.filter(profile__agency=agn_admin) for u in users_of_other_ag: if u.has_perm('users.standardmanager') and u.has_perm('users.agencynetwork'): if u.usernotifications.agn_standard_created_mail: notificationtext = "im Agenturverbund " + agencynetwork_single.name + " wurde ein neuer Standard geteilt: " + standard.name sendMailNoti(notificationtext, u) if u.usernotifications.agn_standard_created_push: newnotification = UserNotification(touser=u, notificationtext="im Agenturverbund " + agencynetwork_single.name + " wurde ein neuer Standard geteilt: " + standard.name, notificationtype="") newnotification.save() channel_layer = channels.layers.get_channel_layer() async_to_sync(channel_layer.group_send)("user_" + str(u.pk), {'type' : 'pushhandler', 'pushtext' : "pushnotification__Agenturverbund | Im Agenturverbund " + agencynetwork_single.name + " wurde ein neuer Standard geteilt: " + standard.name}) for agn_admin in agencynetwork_single.sharemembers.all(): if(agn_admin not in agency_send): agency_send.append(agn_admin) if agn_admin != request.user.profile.agency: users_of_other_ag = User.objects.filter(profile__agency=agn_admin) for u in users_of_other_ag: if u.has_perm('users.standardmanager') and u.has_perm('users.agencynetwork'): if u.usernotifications.agn_standard_created_mail: notificationtext = "im Agenturverbund " + agencynetwork_single.name + " wurde ein neuer Standard geteilt: " + standard.name sendMailNoti(notificationtext, u) if u.usernotifications.agn_standard_created_push: newnotification = UserNotification(touser=u, notificationtext="im Agenturverbund " + agencynetwork_single.name + " wurde ein neuer Standard geteilt: " + standard.name, notificationtype="") newnotification.save() channel_layer = channels.layers.get_channel_layer() async_to_sync(channel_layer.group_send)("user_" + str(u.pk), {'type' : 'pushhandler', 'pushtext' : "pushnotification__Agenturverbund | Im Agenturverbund " + agencynetwork_single.name + " wurde ein neuer Standard geteilt: " + standard.name}) # Clear sended Agencys for multiple Networks agency_send = [] if request.user.has_perm('users.standardmanager'): messages.success(request, f'Standard {standard.name} aktualisiert!') else: if standard.public: standard.public = False messages.warning(request, f'Standard {standard.name} aktualisiert und ist nicht mehr öffentlich, damit Änderungen geprüft werden können.') else: messages.success(request, f'Standard {standard.name} aktualisiert!') standard.save() return redirect('/standards') # SHOW EXISTING STANDARD else: # CHECK IF USER HAS RIGHTS TO SEE THIS DIR groupsofstandard = standard userisingroup = False if len(groupsofstandard.visibleby.all()) == 0: userisingroup = True else: for ag in groupsofstandard.visibleby.all(): if ag.group in request.user.groups.all(): userisingroup = True if userisingroup: normalForm = StandardUpdateStandard(instance=standard) editorForm = StandardUpdateStandardEditor(instance=standard) # TODO: Hier ändern, dass NC die Dateien anbietet! # GET ALL DATAS FROM STANDARD # FILES possibleFilesByVisible = [] #allfiles = DataFile.objects.filter(agency=request.user.profile.agency) # Get all files by view #for f in allfiles: # actParent = DataDir.objects.get(pk=f.parent.pk) # if actParent.is_root: # possibleFilesByVisible.append(f) # else: # if(checkUserDirRights(request, actParent, request.user.pk)): # possibleFilesByVisible.append(f) # Remove files which are in standard #for f in possibleFilesByVisible: # if f in standard.addedfiles.all(): # possibleFilesByVisible.remove(f) filesearchdata = '/files/' + request.user.username + '/Agenturdaten/infinity1' #filesearchdata = 'infinity' r = requests.request("SEARCH", settings.NEXTCLOUD_URL + "remote.php/dav/", data=filesearchdata, headers={'Content-Type' : 'text/xml', 'Authorization' : "Bearer " + request.user.profile.nc_sid}) # IDs filtern aus XML-Response try: split_response = r.text.split("") # Header des XML-Response entfernen split_response.pop(0) # IDs from the User for ele in split_response: new_id = ele.split("")[0] file_free = True # Prüfen, dass diese IDs nicht im aktuellen Standard sind for sf in standard.addedfiles_nc.all(): if str(sf.nc_id) == str(new_id): file_free = False if file_free == True: possibleFilesByVisible.append(new_id) except: pass # STANDARDS possible_standards = [] allstandards = Standards.objects.filter(agency=request.user.profile.agency, public=True) for s in allstandards: if s not in standard.linked_standards.all(): possible_standards.append(s) # USERS VER AUTH EX possible_verant = User.objects.filter(profile__agency__pk=request.user.profile.agency.pk) possible_verant_final = [] for pv in possible_verant: if pv not in standard.authority.all(): possible_verant_final.append(pv) possible_ex = User.objects.filter(profile__agency__pk=request.user.profile.agency.pk) possible_ex_final = [] for pv in possible_ex: if pv not in standard.executor.all(): possible_ex_final.append(pv) possible_ver = User.objects.filter(profile__agency__pk=request.user.profile.agency.pk) possible_ver_final = [] for pv in possible_ver: if pv not in standard.representative.all(): possible_ver_final.append(pv) # GROUPS VER AUTH EX #possible_verant_group_final #possible_ex_group_final #possible_ver_group_final possible_verant_group = AgencyGroup.objects.filter(agency=request.user.profile.agency) possible_verant_group_final = [] for g in possible_verant_group: if g not in standard.authority_group.all(): possible_verant_group_final.append(g) possible_ex_group = AgencyGroup.objects.filter(agency=request.user.profile.agency) possible_ex_group_final = [] for g in possible_ex_group: if g not in standard.executor_group.all(): possible_ex_group_final.append(g) possible_ver_group = AgencyGroup.objects.filter(agency=request.user.profile.agency) possible_ver_group_final = [] for g in possible_ver_group: if g not in standard.representative_group.all(): possible_ver_group_final.append(g) # QUICKLINKS possible_quicklinks = [] quicklinks = QuickLinks.objects.filter(agency=request.user.profile.agency) for q in quicklinks: if q not in standard.addedquicklinks.all(): possible_quicklinks.append(q) # CONTACTS possible_contacts = [] contacts = AGContacts.objects.filter(agency=request.user.profile.agency) for q in contacts: if q not in standard.addedcontacts.all(): possible_contacts.append(q) # PASSWORDS possible_passwords = [] contacts = AGPassword.objects.filter(agency=request.user.profile.agency) for q in contacts: if q not in standard.addedpasswords.all(): possible_passwords.append(q) # AGENCYNETWORKS agencynetworks_all = AgencyNetwork.objects.all() agencynetworks = [] for a in agencynetworks_all: if request.user.profile.agency in a.adminagencys.all() or request.user.profile.agency in a.members.all() or request.user.profile.agency in a.sharemembers.all(): agencynetworks.append(a) # GROUPS # Nicht nötig, da alles über agencygroups und direkt im Standard gemacht wird context = { 'normalForm' : normalForm, 'editorForm' : editorForm, 'standard' : standard, 'files' : possibleFilesByVisible, 'standard_possible' : possible_standards, 'poss_verant' : possible_verant_final, 'poss_ex' : possible_ex_final, 'poss_ver' : possible_ver_final, 'possgroup_verant' : possible_verant_group_final, 'possgroup_ex' : possible_ex_group_final, 'possgroup_ver' : possible_ver_group_final, 'possible_quicklinks' : possible_quicklinks, 'possible_passwords' : possible_passwords, 'possible_contacts' : possible_contacts, 'agencynetworks' : agencynetworks, 'agencygroups' : AgencyGroup.objects.filter(agency=request.user.profile.agency), #'parentid' : list(DataDir.objects.filter(agency=request.user.profile.agency, is_root=True))[0].pk, 'parentid' : 0, 'active_link' : 'standards', 'update' : True, 'aggroups' : AgencyGroup.objects.filter(agency=request.user.profile.agency) } return render(request, 'standards/standards_add.html', context) else: context = { 'active_link':'standards' } return render(request, 'standards/standards_noentrie.html', context) ''' Gibt die Daten der Agenturgruppen zurück, welche in diesem Standard sind. ''' @login_required def LoadAGGroupMembers(request): if request.method == "GET": aggroupid = request.GET['aggroup'] try: aggroup = AgencyGroup.objects.get(pk=aggroupid) except: return JsonResponse({"status" : "err", "message" : "Fehler! Diese Gruppe gibt es nicht."}) members_string = "" if request.user.profile.agency == aggroup.agency: members = User.objects.filter(groups__name=aggroup.group.name) counter = 0 for member in members: members_string += member.get_full_name() counter += 1 if counter+1 <= len(members): members_string += ", " if counter == 0: members_string = "Gruppe hat keine Mitglieder." else: return JsonResponse({"status" : "err", "message" : "Sie haben auf diese Gruppe keinen Zugriff!"}) return JsonResponse({"status" : "ok", "aggroupname" : aggroup.agencygroupname, "members" : members_string}) else: return JsonResponse({"status" : "err", "message" : "Allgemeiner Fehler."}) # Funktion zum versenden einer Mail inkl. TEmplate def sendMailNoti(notificationtext, user_touched, linktarget=""): username = user_touched.first_name + " " + user_touched.last_name msg_html = render_to_string('notificsys/notification_mail.html', {'username': username, 'notificationtext' : notificationtext, 'linktarget' : linktarget}) 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 ) @login_required def load_tasks(request): areaid = request.GET.get('areaid') tasks = Tasks.objects.filter(area__id=areaid, agency=request.user.profile.agency).order_by('name') return render(request, 'standards/standards_tasklist.html', {'tasks': tasks}) class StandardDeleteView(LoginRequiredMixin, DeleteView): model = Standards success_url = '/standards' template_name = 'standards/standard_confirm_delete.html' def delete(self, request, *args, **kwargs): standard = Standards.objects.get(pk=kwargs['pk'], agency=request.user.profile.agency) response = super(StandardDeleteView, self).delete(request, *args, **kwargs) names = standard.name messages.success(request, f'Standard ' +names+ ' wurde gelöscht!') return response def get_context_data(self, **kwargs): context = super(StandardDeleteView, self).get_context_data(**kwargs) context['active_link'] = 'standards' return context @login_required def StandardChangePublic(request, pk): standard = Standards.objects.get(pk=pk) if standard.public: standard.public = False messages.warning(request, f'Standard {standard.name} ist nicht mehr öffentlich!') else: standard.public = True messages.success(request, f'Standard {standard.name} wurde veröffentlicht und ist innerhalb der Agentur sichtbar!') standard.save() return redirect('standards') @login_required def StandardSingle(request, pk): # CHECK IF USER HAS RIGHTS TO SEE THIS DIR groupsofstandard = Standards.objects.get(pk=pk, agency=request.user.profile.agency) userisingroup = False if len(groupsofstandard.visibleby.all()) == 0: userisingroup = True else: for ag in groupsofstandard.visibleby.all(): if ag.group in request.user.groups.all(): userisingroup = True if userisingroup: standard = Standards.objects.get(pk=pk) context = { 'active_link':'standards', 'standard' : standard } return render(request, 'standards/standards_single.html', context) else: context = { 'active_link':'standards' } return render(request, 'standards/standards_noentrie.html', context) @login_required def CopyStandard(request, pk): #SANDARD COPY sc = Standards.objects.get(pk=pk) sc.agencynetworkcounter = sc.agencynetworkcounter+1 sc.save() area = list(Areas.objects.filter(agency=request.user.profile.agency))[0] task = list(Tasks.objects.filter(agency=request.user.profile.agency))[0] new_standard = Standards() new_standard.agency = request.user.profile.agency new_standard.created_standard_by = request.user new_standard.published_by = request.user new_standard.last_modified_by = request.user new_standard.created_standard_date = datetime.now() new_standard.last_modified_on = datetime.now() new_standard.task = None new_standard.area = None new_standard.name = sc.name new_standard.content = sc.content new_standard.public = False new_standard.freefield_content = sc.freefield_content new_standard.freefield_title = sc.freefield_title new_standard.parent_standard = sc new_standard.shared_on = datetime.now() new_standard.save() #datadir_parentid = list(DataDir.objects.filter(is_defaultstandard=True, agency__pk=request.user.profile.agency.pk))[0] for f in sc.addedfiles_nc.all(): tempdatafile = NCFile(agency=request.user.profile.agency, nc_id=f.nc_id) tempdatafile.save() new_standard.addedfiles_nc.add(tempdatafile) # Sende Info, dass ein Standard übernommen wurde, an die Erstelleragentur usersofagency = User.objects.filter(profile__agency=sc.agency) for u in usersofagency: if u.has_perm('users.standardmanager') and u.has_perm('users.agencynetwork'): if u.usernotifications.agn_standard_copied_mail: notificationtext = "der Standard " + sc.name + " wurde von der Agentur " + request.user.profile.agency.name + " übernommen." sendMailNoti(notificationtext, u) if u.usernotifications.agn_standard_copied_push: newnotification = UserNotification(touser=u, notificationtext="der Standard " + sc.name + " wurde von der Agentur " + request.user.profile.agency.name + " übernommen.", notificationtype="") newnotification.save() channel_layer = channels.layers.get_channel_layer() async_to_sync(channel_layer.group_send)("user_" + str(u.pk), {'type' : 'pushhandler', 'pushtext' : "pushnotification__Agenturverbund | Der Standard " + sc.name + " wurde von der Agentur " + request.user.profile.agency.name + " übernommen."}) return redirect('standard-add', new_standard.pk) @login_required def StandardArea(request, pk): standards = Standards.objects.filter(agency__pk=request.user.profile.agency.pk).exclude(area=None).exclude(task=None).filter(area__pk=pk) area = Areas.objects.get(pk=pk, agency=request.user.profile.agency) context = { 'active_link':'standards', 'standards_of_agency_area' : standards, 'areaid' : pk, 'areaname' : area.name } return render(request, 'standards/standard_area.html', context) @login_required def StandardTask(request, pk): standards = Standards.objects.filter(agency__pk=request.user.profile.agency.pk).exclude(area=None).exclude(task=None).filter(task__pk=pk) task = Tasks.objects.get(pk=pk, agency=request.user.profile.agency) area = Areas.objects.get(pk=task.area.pk, agency=request.user.profile.agency) context = { 'active_link':'standards', 'standards_of_agency_task' : standards, 'taskid' : pk, 'taskname' : task.name, 'areaid' : area.pk, 'areaname' : area.name } return render(request, 'standards/standard_task.html', context) @login_required def StandardTaskUser(request, pk, userpk): standards = Standards.objects.filter(agency__pk=request.user.profile.agency.pk, created_standard_by=User.objects.get(pk=userpk)).exclude(area=None).exclude(task=None).filter(task__pk=pk) or Standards.objects.filter(agency__pk=request.user.profile.agency.pk, last_modified_by=User.objects.get(pk=userpk)).exclude(area=None).exclude(task=None).filter(task__pk=pk) task = Tasks.objects.get(pk=pk, agency=request.user.profile.agency) area = Areas.objects.get(pk=task.area.pk, agency=request.user.profile.agency) context = { 'active_link':'standards', 'standards_of_agency_task' : standards, 'taskid' : pk, 'taskname' : task.name, 'areaid' : area.pk, 'areaname' : area.name, 'vieweduser' : User.objects.get(pk=userpk) } return render(request, 'standards/standard_task_user.html', context) # AJAX Standard @login_required def updatesbyajax(request, pk): if(request.method == "GET"): success = True workingstandard = Standards.objects.get(pk=pk, agency=request.user.profile.agency) # Check for correct user and userrights if(request.user.profile.agency == workingstandard.agency and request.user.has_perm("users.standardmanager")): # CHANGE GROUP # ADD if(request.GET["action"] == "s_addgroup"): workingstandard.visibleby.add(AgencyGroup.objects.get(pk=request.GET["groupid"], agency=request.user.profile.agency)) # REMOVE elif(request.GET["action"] == "s_remgroup"): workingstandard.visibleby.remove(AgencyGroup.objects.get(pk=request.GET["groupid"], agency=request.user.profile.agency)) # FILES # REMOVE elif(request.GET["action"] == "s_remfile"): workingstandard.addedfiles.remove(DataFile.objects.get(pk=request.GET["fileid"], agency=request.user.profile.agency)) # ADD elif(request.GET["action"] == "s_addfile"): workingstandard.addedfiles.add(DataFile.objects.get(pk=request.GET["fileid"], agency=request.user.profile.agency)) # STANDARD # REMOVE elif(request.GET["action"] == "s_remstandard"): workingstandard.linked_standards.remove(Standards.objects.get(pk=request.GET["standardid"], agency=request.user.profile.agency)) # ADD elif(request.GET["action"] == "s_addstandard"): workingstandard.linked_standards.add(Standards.objects.get(pk=request.GET["standardid"], agency=request.user.profile.agency)) # VERANTWORTLICHER / AUTHORITY # REMOVE elif(request.GET["action"] == "s_remverant"): workingstandard.authority.remove(User.objects.get(pk=request.GET["userid"], profile__agency=request.user.profile.agency)) elif(request.GET["action"] == "s_addverant"): workingstandard.authority.add(User.objects.get(pk=request.GET["userid"], profile__agency=request.user.profile.agency)) # ASUFÜRHENDER / EXECUTOR # REMOVE elif(request.GET["action"] == "s_remex"): workingstandard.executor.remove(User.objects.get(pk=request.GET["userid"], profile__agency=request.user.profile.agency)) elif(request.GET["action"] == "s_addex"): workingstandard.executor.add(User.objects.get(pk=request.GET["userid"], profile__agency=request.user.profile.agency)) # VERTRETER / REPRESENETATIVE # REMOVE elif(request.GET["action"] == "s_remver"): workingstandard.representative.remove(User.objects.get(pk=request.GET["userid"], profile__agency=request.user.profile.agency)) elif(request.GET["action"] == "s_addver"): workingstandard.representative.add(User.objects.get(pk=request.GET["userid"], profile__agency=request.user.profile.agency)) # ADD STANDARD TO AGENCYNETWORK elif(request.GET["action"] == "s_addtonetwork"): if workingstandard.public and request.user.profile.agency == workingstandard.agency: agn = AgencyNetwork.objects.get(pk=request.GET["agn_id"]) if(request.GET["newstat"] == "true"): agn.standards.add(workingstandard) else: agn.standards.remove(workingstandard) agn.lastactivity = datetime.now() agn.save() else: success = False return JsonResponse({"success" : success}) # CREATE PDF FROM STANDARD from io import BytesIO from xhtml2pdf import pisa # Utility function def convert_html_to_pdf(source_html, output_filename): result = BytesIO() pdf = pisa.pisaDocument(BytesIO(source_html.encode("UTF-8")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None @login_required def getStandardPDF(request, pk): standard = Standards.objects.get(pk=pk) # CHECK IF USER HAS RIGHTS TO SEE THIS Standard groupsofstandard = Standards.objects.get(pk=pk, agency=request.user.profile.agency) userisingroup = False if len(groupsofstandard.visibleby.all()) == 0: userisingroup = True else: for ag in groupsofstandard.visibleby.all(): if ag.group in request.user.groups.all(): userisingroup = True if userisingroup: pdf = convert_html_to_pdf("

" + standard.name + "


" + standard.content, "final.pdf") return HttpResponse(pdf, content_type='application/pdf') else: messages.warning(request, f'Diesen Standard dürfen Sie nicht sehen!') return redirect('standards') @login_required def StandardFromAgn(request, pk): try: agn = AgencyNetwork.objects.get(pk=pk) context = { 'active_link':'standards', 'standards_of_agency_network' : agn.standards.all(), 'agn' :agn, } return render(request, 'standards/standards_from_agn.html', context) except: context = { 'active_link':'standards', } return redirect('standards') # View for SingleStandard from AgencyNetwork @login_required def StandardSingleAgn(request, pk, agnpk): context = { 'active_link':'standards', 'agnpk' : agnpk, 'standard' : Standards.objects.get(pk=pk), 'comments' : StandardComments.objects.filter(standard=Standards.objects.get(pk=pk)).order_by("-last_modified_on") } return render(request, 'standards/standards_single_agn.html', context) @login_required def updatesbyajax_agn(request, pk): if(request.method == "GET"): if(request.GET["action"] == "add_comment"): content = re.sub('[^A-Za-z0-9,!?_ äüöÄÜÖ]+', '', request.GET.get("content")) sc = StandardComments(standard=Standards.objects.get(pk=pk), content=content, comment_by=request.user, comment_on=datetime.now(), last_modified_on=datetime.now()) sc.save() # Benachrichtigung an Standardagentur standard_comment = Standards.objects.get(pk=pk) usersofagency = User.objects.filter(profile__agency=standard_comment.agency) for u in usersofagency: if u.has_perm('users.standardmanager'): if u.usernotifications.agn_standard_comment_mail: notificationtext = "der Standard " + standard_comment.name + " wurde kommentiert: " + content sendMailNoti(notificationtext, u) if u.usernotifications.agn_standard_comment_push: newnotification = UserNotification(touser=u, notificationtext="der Standard " + standard_comment.name + " wurde kommentiert: " + content, notificationtype="") newnotification.save() channel_layer = channels.layers.get_channel_layer() async_to_sync(channel_layer.group_send)("user_" + str(u.pk), {'type' : 'pushhandler', 'pushtext' : "pushnotification__Agenturverbund | Der Standard " + standard_comment.name + " wurde kommentiert:" + content}) return JsonResponse({"success" : "success", "sc_id" : sc.pk, "sc_c" : sc.content, "sc_user" : sc.comment_by.first_name + " " + sc.comment_by.last_name, "sc_date" : defaultfilters.date(sc.last_modified_on, "SHORT_DATETIME_FORMAT") }) elif(request.GET["action"] == "del_comment"): StandardComments.objects.get(pk=request.GET.get("id")).delete() return JsonResponse({}) elif(request.GET["action"] == "update_comment_rate"): user = request.user comment = StandardComments.objects.get(pk=request.GET.get("id")) rate = list(StandardCommentRate.objects.filter(oncomment=comment, rated_by=request.user)) if len(rate) == 0: new_s_c_rate = StandardCommentRate(oncomment=comment, rated_by=request.user, rate_stats=request.GET.get("newstat")) new_s_c_rate.save() else: s_c_rate = StandardCommentRate.objects.get(pk=rate[0].pk) s_c_rate.rate_stats=request.GET.get("newstat") s_c_rate.save() counter_up = len(StandardCommentRate.objects.filter(oncomment=comment, rate_stats=1)) counter_down = len(StandardCommentRate.objects.filter(oncomment=comment, rate_stats=0)) u = comment.comment_by if u.usernotifications.agn_standard_comment_react_mail: notificationtext = "der Kommentar zum Standard " + comment.standard.name + " wurde gerated!" sendMailNoti(notificationtext, u) if u.usernotifications.agn_standard_comment_react_push: newnotification = UserNotification(touser=u, notificationtext="der Kommentar zum Standard " + comment.standard.name + " wurde gerated!", notificationtype="") newnotification.save() channel_layer = channels.layers.get_channel_layer() async_to_sync(channel_layer.group_send)("user_" + str(u.pk), {'type' : 'pushhandler', 'pushtext' : "pushnotification__Kommantar | der Kommentar zum Standard " + comment.standard.name + " wurde gerated!"}) return JsonResponse({"up" : counter_up, "down" : counter_down}) elif(request.GET["action"] == "markingfavorit"): workingstandard = Standards.objects.get(pk=pk) added = False if workingstandard.public: if(request.user in workingstandard.favoritfrom.all()): workingstandard.favoritfrom.remove(request.user) else: workingstandard.favoritfrom.add(request.user) added = True return JsonResponse({"added" : added}) @login_required def UpdateStandardBeforeUserDel(request): if(request.method == "GET"): success = False # Get Request-Data newuser = User.objects.get(pk=request.GET["userid"]) finalkind = request.GET["finalkind"] standard = Standards.objects.get(pk=request.GET["standard"]) useractor = User.objects.get(pk=request.GET["useractorid"]) if(newuser.profile.agency == useractor.profile.agency and standard.agency == useractor.profile.agency and useractor.has_perm('users.usermanager')): # User is new creator if(finalkind == "created"): standard.created_standard_by = newuser # User is new executor elif(finalkind == "ex"): standard.executor.add(newuser) # User is new representator elif(finalkind == "repr"): standard.representative.add(newuser) # User is new in auth elif(finalkind == "auth"): standard.authority.add(newuser) standard.save() success = True else: success = False return JsonResponse({"success" : success}) ''' UPLOADING A FILE Replace the function in the App CLOUD ''' @login_required def uploadFileFromStandard(request): success = True if request.method == 'POST': request.decoding = 'utf-8' # VALIDATE FILE-TYPE file_ext_arr = request.FILES['uploadedfile'].name.split(".") file_ext = file_ext_arr[len(file_ext_arr)-1] allowed_types = ["txt", "TXT", "png", "PNG", "jpeg", "JPEG", "jpg", "JPG", "PDF", "pdf", "csv", "CSV", "DOC", "doc", "DOCX", "docx", "ODT", "odt", "PPT", "ppt", "PPTX", "pptx", "XLS", "xls", "XLSX", "xlsx", "xlsm", "XLSM", "mov", "MOV", "SVG", "svg", "ZIP", "zip", "RAR", "rar", "EPS", "eps", "MP3", "mp3", "WAV", "wav", "avi", "AVI", "FLV", "flv", "MP4", "mp4", "PAGES", "pages", "NUMBERS", "numbers", "ics", "ICS"] file_ok = False for t in allowed_types: if t == file_ext: file_ok = True if(file_ok): final_file_path = settings.NEXTCLOUD_URL + "remote.php/dav/files/" + request.user.username + "/Agenturdaten/Standards Uploadbereich/" + request.FILES['uploadedfile'].name # Check if File already exist try: new_file_name = request.FILES['uploadedfile'].name filesearchdata = '/files/' + request.user.username + 'infinity' + new_file_name + '' r = requests.request("SEARCH", settings.NEXTCLOUD_URL + "remote.php/dav/", data=filesearchdata, headers={'Content-Type' : 'text/xml;', 'Authorization' : "Bearer " + request.user.profile.nc_sid}) #print(r.text) split_response = r.text.split("") new_id = split_response[1].split("")[0] return JsonResponse({"success" : False, "data" : "file exist"}) except: # File will be uploaded r = requests.put(final_file_path, data=request.FILES['uploadedfile'], headers={'Content-Type' : 'text/xml;', 'Authorization' : "Bearer " + request.user.profile.nc_sid}) if(len(r.text) == 0): try: new_file_name = request.FILES['uploadedfile'].name # Upload OK - get File-ID in NC filesearchdata = '/files/' + request.user.username + 'infinity' + new_file_name + '' r = requests.request("SEARCH", settings.NEXTCLOUD_URL + "remote.php/dav/", data=filesearchdata, headers={'Content-Type' : 'text/xml;', 'Authorization' : "Bearer " + request.user.profile.nc_sid}) #print(r.text) split_response = r.text.split("") new_id = split_response[1].split("")[0] tf = NCFile(agency=request.user.profile.agency, nc_id=new_id) tf.save() return JsonResponse({"success" : success, "data" : {'savedobj_id' : new_id, 'savedobj_name' : new_file_name}}) except: success = True return JsonResponse({"success" : success, "data" : {'savedobj_id' : None, 'savedobj_name' : 'Datei hochgeladen, enthält aber falsche Zeichen. Bitte speichern Sie den Standard, laden die Seite ne und binden die Datei danach ein.'}}) return JsonResponse({"success" : success, "data" : "DONE!"}) return JsonResponse({"success" : success, "data" : "DONE!"})