def create_chatmessage(sender, instance, created, **kwargs): if created: chat = instance.chat room = chat.room if room: link_to = room.path else: link_to = f'/chat/{chat.id}' content = { 'title': f'Новое сообщение', 'content1': f'В чате ', 'link_to': link_to, 'link_text': f'{chat.first_user}-{chat.second_user}', 'content2': ' есть новые сообщения', 'n_type': NOTIF_ROOM_CHAT_NEW_MESSAGE, 'chat': chat.id, } if not room: content['n_type'] = NOTIF_PRIVATE_CHAT_NEW_MESSAGE if chat.first_user.id != instance.sender.id: delete_same_notifs(chat.first_user, {'chat': chat.id}) Notification(user=chat.first_user, **content).save() else: delete_same_notifs(chat.second_user, {'chat': chat.id}) Notification(user=chat.second_user, **content).save() else: for user in room.admin_list.all(): if user.id != instance.sender.id: delete_same_notifs(user, {'chat': chat.id}) Notification(user=user, **content).save() for user in room.allowed_users.all(): if user.id != instance.sender.id: delete_same_notifs(user, {'chat': chat.id}) Notification(user=user, **content).save()
def product_expiry_reminder_task(text): today = datetime.date.today() superusers = User.objects.filter(is_superuser=True, is_active=True) instances = ProductExpiryDate.objects.filter(is_deleted=False, expiry_date__gte=today) for instance in instances: if instance.product.product_expiry_before: to_date = today + datetime.timedelta( days=instance.product.product_expiry_before) if to_date <= instance.expiry_date: subject = NotificationSubject.objects.get( code="expiry_notification") for user in superusers: Notification(user=user, subject=subject, product=instance.product, shop=instance.shop, is_active=True, expiry_date=instance).save() staffs = Staff.objects.filter(is_deleted=False) for staff in staffs: user = staff.user if staff.permissionlist: permlist = [ str(x.code) for x in staff.permissions.all() ] if 'can_view_product' in permlist: Notification(user=staff.user, subject=subject, product=instance.product, is_active=True, shop=instance.shop, expiry_date=instance).save() return "Completed"
def accept_application(self, leader_user) -> None: """ Accepts an application and adds the user to the fond. Furthermore, everyone in the fond will get a notification that a new member has been added to the fond. """ subject = f"Welcome to {self.fond}" text = ( f"Your application has been accepted. You have joined {self.fond}\n\n" f"Best regards, {leader_user} - {self.fond}") Member.objects.create(user_id=self.user_id, fond=self.fond) notifications = [] for member in self.fond.member_set.all(): notifications.append( Notification( user_id=member.user_id, text=f"Welcome {self.user} in your fond!", subject=f"{self.user} joined {self.fond}", )) notifications.append( Notification(user=self.user, subject=subject, text=text)) notifications = Notification.objects.bulk_create(notifications) for obj in notifications: e = Event(user_id=obj.user_id, typ="Notification", msg=obj.subject) store_event(e)
def addNotification(request, secondUser, postID, notificationState, isAdd): post = None try: post = get_object_or_404(Post, id=postID) except: pass currUser = get_object_or_404(MyUser, user=request.user) tmpUser = secondUser notification = Notification() notification.firstUser = currUser notification.secondUser = tmpUser notification.post = post notification.notificationState = notificationState if isAdd: currUser.first.add(notification) tmpUser.second.add(notification) else: Notification.objects.filter(firstUser=notification.firstUser).filter(secondUser=notification.secondUser) \ .filter(post=notification.post) \ .filter(notificationState=notification.notificationState).delete()
def view_question(request, question_slug): question = get_object_or_404(Question, slug=question_slug, active=True) if request.method == 'POST': response_form = ResponseCreateForm(request.POST) print(request.POST) if response_form.is_valid(): new_response = response_form.save(commit=False) new_response.author = request.user new_response.parent_question = question new_response.save() noti = Notification( title= f'{request.user} responded to your question "{question.title[:50]}"!', user=question.author.profile) noti.save() return redirect('view_question', question.slug) response_form = ResponseCreateForm(auto_id='response_%s') question_edit_form = None if question.author == request.user: question_edit_form = QuestionEditForm(instance=question) return render( request, 'discussions/view.html', { 'question': question, 'response_form': response_form, 'question_edit_form': question_edit_form, })
def upvote(request, question_slug): result = {'success': True, 'code': '', 'upvotes': 0, 'downvotes': 0} question = get_object_or_404(Question, slug=question_slug, active=True) votes = question.votes.filter(user=request.user) if votes: vote = votes.first() if vote.family == True: vote.delete() result['code'] = 'REMOVED_UPVOTE' else: vote.family = True vote.save() result['code'] = 'DOWNVOTE_TO_UPVOTE' else: vote = Vote(content_object=question, user=request.user, family=True) vote.save() result['code'] = 'ADDED_UPVOTE' noti = Notification( title= f'{request.user} upvoted your question "{question.title[:50]}"!', user=question.author.profile) noti.save() result['upvotes'] = question.votes.filter(family=True).count() result['downvotes'] = question.votes.filter(family=False).count() return HttpResponse(json.dumps(result), content_type="application/json")
def create_invitation(user_to, from_user, team_to): new_invitation = JoinInvitation(to_user=user_to, team=team_to) new_invitation.save() new_notification = Notification( user = user_to, category = "Invitación de equipo", text = f'{from_user} te ha invitado a unirte a su equipo: "{team_to}".', join_invitation = new_invitation ) new_notification.save()
def mark_all_as_read(request): """ Set all the notifications as read. @param request: the incoming request data. @return: returns to the referer page with all the notifications set as read. """ Notification.set_all_as_read(request.user) return redirect(request.META['HTTP_REFERER'])
def notify_users(room_obj, verb=''): users_in_room = room_obj.room.user_rooms.all() users_in_room = [profile.user for profile in users_in_room] for user in users_in_room: if user != room_obj.posted_by: notification = Notification(actor=room_obj.posted_by, verb=verb, action_obj=room_obj, target=user) notification.save()
def retrieve_device_usageDB(device, massive): #IMEI:353918057929438 2013-11-22+02:00 t_now = datetime.now() end = t_now.strftime("%Y-%m-%d+%H:%M") print "Last check:", device.last_checked print "Time now:", end deviceApps = device.application_set.all() for app in deviceApps: print "this device already has", app.session_set.all(), app.appname, "sessions" print "===================== notifications" get_notifications(device) if device.last_checked == end: print "No time elapsed since last check" return device.last_checked = end if massive: start = (t_now - timedelta(days=30)).strftime("%Y-%m-%d+%H:%M") else: start = (t_now - timedelta(minutes=5)).strftime("%Y-%m-%d+%H:%M") print "Checking usage for time:", start, "until", end url = 'https://tethys.dcs.gla.ac.uk/AppTracker/api/v2/log?key=%s&device=%s&from=%s&to=%s' % (API_KEY, device.device_id, start, end) print url sessions = json.load(urllib2.urlopen(url)) print "There are :", len(sessions), "new sessions" for session in sessions: print session['app'] print deviceApps app = deviceApps.filter(appname=session["app"]) print app if len(app) == 0: app = Application(device=device, appname=session['app'], total_time=session['timespent']) app.save() sesh = Session(dev_app=app, time_spent=session['timespent'], time_stamp=session['timestamp']) print app.appname else: app = app[0] sesh = Session(dev_app=app, time_spent=session['timespent'], time_stamp=session['timestamp']) app.total_time += session['timespent'] app.save() sesh.save() if not massive and ((sesh.time_spent / 1000) > 1): print "added a notification" notification = Notification(device=device,session=sesh, time_stamp=sesh.time_stamp) notification.save() sendmail("Appage", "You have a new notification", device.owner.email) device.save()
def send_sharing_notification(self, inviter, allowed_user, instance): if getattr(allowed_user, 'id', False): try: notification = Notification( title=f"You now have access to {instance.client}", content= f"{inviter.name} has shared the scenario for {instance.client} with you.", type="scenario_share", read=False, target=allowed_user) notification.save() except Exception as e: print(e) else: # The user does not have an account, create a notification but use # the "to" field instead of target. Will be assigned on acc creation. # Assignment of notification on account creation must also add them # as an allowed_user using the newly created user instance. try: notification = Notification( title=f"You now have access to {instance.client}", content= f"{inviter.name} has shared the scenario for {instance.client} with you.", type="scenario_share", read=False, to=allowed_user['email']) notification.save() except Exception as e: print(e)
def add_staff_notification(self, inviter, user, practice): ''' Creates a new notification when a user is added to a practice. Allows the added user to accept the invitation. ''' if isinstance(user, str): #If no account exists try: notification = Notification(title="Practice Invitation", content=f"{self.get_inviter(inviter)} has invited you to join {practice.name}", type="practice_invite", read=False, to=user, practice=practice) notification.save() except Exception as e: print(e) else: #If account exists. try: notification = Notification(title="Practice Invitation", content=f"{self.get_inviter(inviter)} has invited you to join {practice.name}", type="practice_invite", read=False, target=user, practice=practice) notification.save() except Exception as e: print(e)
def addNotification(request, secondUser, postID, notificationState, isAdd): post = None try: post = get_object_or_404(Post, id=postID) except: pass currUser = get_object_or_404(MyUser, user=request.user) tmpUser = secondUser notification = Notification() notification.firstUser = currUser notification.secondUser = tmpUser notification.post = post notification.notificationState = notificationState notification.save() if isAdd: currUser.first.add(notification) tmpUser.second.add(notification) else: Notification.objects.filter(firstUser=notification.firstUser).filter(secondUser=notification.secondUser) \ .filter(post=notification.post) \ .filter(notificationState=notification.notificationState).delete()
def saveTaskActivity(on_task, by_user, with_description, recipients): print("on savetaskactivity function") new_task_activity = TaskActivity(task=on_task, user=by_user, description=with_description) new_task_activity.save() for recipient in recipients: if recipient != by_user: new_notification = Notification( user=recipient, category= f'Actividad en la tarea "{on_task}" del proyecto "{on_task.project}"', text=with_description, task_activity=new_task_activity) new_notification.save()
def get_all_user_achievements(request): user = UserService.logged_in_user(request) achievements = Achievement.objects.all() data = [] for ach in achievements: result = engine.check_achievement(user=user, key=ach.key) data.append(result) if result["new"]: n = Notification(name=result["name"] + " Earned", description=result["description"], icon=result["icon"], user=user) n.save() return JsonResponse({"data": data})
def create_notification(self, user_id, amount, value): subject = f"{amount} Bonds paid out!" text = f"{amount} have been paid out. You received a total of {value}$!" notification = Notification(user_id=user_id, subject=subject, text=text) self.notifications.append(notification)
def notificate_report(site_user, element_id): users = SiteUser.objects.filter(is_superuser=True) mails = [] for user in users: notification = Notification( a_tag='', user=user, message='El usuario '+site_user.first_name+' '+site_user.last_name+' ha enviado un reporte para revisar.</a>'.decode('utf-8'), short=u"Nuevo Reporte", icon="fa fa-text-file" ) mails.append(user.email) notification.save() notification.a_tag='<a href="/estudios/ver/'+str(element_id)+'?notif='+str(notification.id)+'">' notification.save() send_mail( subject=u'Nuevo reporte', message='Se ha enviado un reporte para revisar.', html_message='<p>El usuario '+site_user.first_name+' '+site_user.last_name+' ha enviado un reporte para revisar. <a href="ursus.cosegem.com/estudios/ver/'+str(element_id)+'?notif='+str(notification.id)+'">Ver reporte</a></p>'.decode('utf-8'), from_email='Ursus <*****@*****.**>', recipient_list=mails, fail_silently=False )
def notificate_requisition(site_user, element_id): users = User.objects.filter(is_superuser=True) mails = [] for user in users: mails.append(user.email) notification = Notification( a_tag='', user=user, message='El cliente ' + site_user.first_name + ' ' + site_user.last_name + ' ha registrado una nueva requisición.</a>'.decode('utf-8'), short=u"Nueva requisición", icon="fa fa-book") notification.save() notification.a_tag = '<a href="/requisiciones/ver/' + str( element_id) + '?notif=' + str(notification.id) + '">' notification.save() send_mail( subject=u'Nueva requisición registrada', message='El cliente ' + site_user.first_name + ' ' + site_user.last_name + ' ha registrado una nueva requisicion.', html_message='<p>El cliente <b>' + site_user.first_name + ' ' + site_user.last_name + '</b> ha registrado una nueva requisicion. <a href="ursus.cosegem.com/requisiciones/ver/' + str(element_id) + '?notif=' + str(notification.id) + '">Ver requisicion</a></p>'.decode('utf-8'), from_email='Ursus <*****@*****.**>', recipient_list=mails, fail_silently=False)
def __call__(self, request): ################### # On client request ################### token = request.META.get("HTTP_AUTHORIZATION", None) def pre(x): return request.path == x or request.path == (x + "/") req = None # Identify which view the request is associated with if ach attached. for v in self.views: if pre(v.url): req = v.view if req is not None: req = View.objects.get(view=req) tasks = Task.objects.filter(views=req) response = self.get_response(request) #################### # On server response #################### if token is None or response.content is None or req is None: return response #data = json.loads(response.content.decode('utf-8')) #data['achievement'] = [] user = token_to_user_course(token) for t in tasks: achievements = t.achievements.all() for a in achievements: result = engine.check_achievement(user=user, key=a.key) if result["new"]: n = Notification(name=result["name"] + " Earned", description=result["description"], icon=result["icon"], user=user) n.save() return response
def create_store_notification(instance, created, **kwargs): if created: # users = AuthUserModel.objects.filter(is_staff=False).all() users = AuthUserModel.objects.exclude(is_staff=True).all() for user in users: Notification( user=user, content_object=instance, message='New store was added.', link=reverse('stores:details', args=(instance.id, )), ).save()
def form_valid(self, form): artwork = Artwork.objects.get(pk=self.kwargs['artworkid']) self.success_url += str(self.kwargs['picnicid']) + "/artwork/" + str( self.kwargs['artworkid']) form.instance.critiquer = self.request.user form.save() artwork.critiques.add(form.instance) membership = Membership.objects.filter( member=self.request.user, group=Picnic.objects.get(id=self.kwargs['picnicid']))[0] membership.num_critiques += 1 membership.save() n = Notification(message=self.request.user.username + " has critiqued your piece \"" + artwork.title + ".\"", \ picnicid=self.kwargs['picnicid'], artworkid=self.kwargs['artworkid']) n.save() pUser = PicnicUser.objects.get(user=artwork.artist) pUser.notifs.add(n) pUser.hasNotifications = True pUser.save() return super().form_valid(form)
def create_pizza_notification(instance, **kwargs): if instance.pk: # object was already saved at a previous time. current_price = Pizza.objects.get(pk=instance.pk).price if instance.price < current_price: users = AuthUserModel.objects.exclude(is_staff=True).all() for user in users: Notification( user=user, content_object=instance, message='Pizza price have dropped!', link=reverse('stores:pizza:details', args=(instance.id, )), ).save()
def notificate_requisition(site_user, element_id): users = User.objects.filter(is_superuser=True) mails = [] for user in users: mails.append(user.email) notification = Notification( a_tag='', user=user, message='El cliente '+site_user.first_name+' '+site_user.last_name+' ha registrado una nueva requisición.</a>'.decode('utf-8'), short=u"Nueva requisición", icon="fa fa-book" ) notification.save() notification.a_tag='<a href="/requisiciones/ver/'+str(element_id)+'?notif='+str(notification.id)+'">' notification.save() send_mail( subject=u'Nueva requisición registrada', message='El cliente '+site_user.first_name+' '+site_user.last_name+' ha registrado una nueva requisicion.', html_message='<p>El cliente <b>'+site_user.first_name+' '+site_user.last_name+'</b> ha registrado una nueva requisicion. <a href="ursus.cosegem.com/requisiciones/ver/'+str(element_id)+'?notif='+str(notification.id)+'">Ver requisicion</a></p>'.decode('utf-8'), from_email='Ursus <*****@*****.**>', recipient_list=mails, fail_silently=False )
def response_upvote(request, question_slug, response_pk): result = {'success': True, 'code': '', 'upvotes': 0, 'downvotes': 0} response = get_object_or_404(Response, pk=response_pk) votes = response.votes.filter(user=request.user) if votes: vote = votes.first() if vote.family == True: vote.delete() result['code'] = 'REMOVED_UPVOTE' else: vote.family = True vote.save() result['code'] = 'DOWNVOTE_TO_UPVOTE' else: vote = Vote(content_object=response, user=request.user, family=True) vote.save() result['code'] = 'ADDED_UPVOTE' if request.user != response.author: noti = Notification( title= f'{request.user} upvoted your response on "{response.parent_question.title[:50]}" !', user=response.author.profile) noti.save() result['upvotes'] = response.votes.filter(family=True).count() result['downvotes'] = response.votes.filter(family=False).count() return HttpResponse(json.dumps(result), content_type="application/json")
def create_answer(sender, instance, created, **kwargs): if created: question = instance.question room = question.question_page.room user = question.creator content = { 'title': f'Новый ответ на вопрос', 'content1': f'На ваш вопрос {question.title} в комнате ', 'link_to': f"/{room.path}", 'link_text': room.name, 'content2': ' есть новые сообщения', 'n_type': NOTIF_NEW_ANSWER, 'question': question.id, 'user': user } delete_same_notifs(user, {'question': question.id}) Notification(**content).save()
def create_notification(request): if request.method == 'POST': patient_id = request.POST.get('patient_id') doctor_id = request.POST.get('doctor_id') complaints = request.POST.get('complaints') date = request.POST.get('date') hospital_id = request.POST.get('hospital_id') repeat_visit = request.POST.get('repeat_visit') doctor_profile = DoctorProfile.objects.get(user_id=doctor_id) patient_profile = PatientProfile.objects.get(user_id=patient_id) hospital = Hospital.objects.get(pk=hospital_id) notification = Notification(complaints=complaints, date=date) notification.patient_profile = patient_profile notification.doctor_profile = doctor_profile notification.hospital = hospital if repeat_visit == 'true': notification.visit_number = 2 notification.save() return JsonResponse({"message": "OK"}, static=201)
def send_notifications(user, email_subject, email_template, context, post=None): """ Sends the email and the real-time notifications to the users. @param user: the user that will get the notification. @param email_subject: the email's subject. @param email_template: the email's template. @param context: the contents of the notification. @param post: In case it is a post-related notification will be a post instance. """ # email_notification_for_user(user, email_subject, email_template, context) if post is not None: new_notification = Notification(message=context['content'], status=False, user=user, post=post, type=1) else: new_notification = Notification(message=context['content'], status=False, user=user, type=0) new_notification.save()
def notificate_assignation(site_user, element_id): notification = Notification( a_tag='', user=site_user, message='Se le ha asignado un nuevo estudio.</a>'.decode('utf-8'), short=u"Nueva asignación", icon="fa fa-search") notification.save() notification.a_tag = '<a href="/estudios/ver/' + str( element_id) + '?notif=' + str(notification.id) + '">' notification.save() send_mail( subject=u'Nueva asignación', message='Se le ha asignado un nuevo estudio.', html_message= '<p>Se le ha asignado un nuevo estudio. Para mayor detalle use <a href="ursus.cosegem.com/estudios/ver/' + str(element_id) + '?notif=' + str(notification.id) + '">este enlace</a></p>'.decode('utf-8'), from_email='Ursus <*****@*****.**>', recipient_list=[site_user.email], fail_silently=False)
def create_notification(self, user: User, amount: int, price: Decimal, order_of: Company, received: bool): notification = Notification.order(user, amount, price, order_of, received) self.notfications.append(notification)
def joinPicnic(request): if request.method == 'POST': form = PicnicJoinForm(request.POST) if form.is_valid(): # form.save() key = form.cleaned_data.get('key') picnic_exists = False for picnic in Picnic.objects.all(): if picnic.key == key: picnic_exists = True is_member = False for membership in picnic.members.all(): if membership == request.user: is_member = True if not is_member: print(len(picnic.members.all())) if len(picnic.members.all()) < 15: m = Membership(group=picnic, member=request.user, nickname=request.user.username) m.save() # picnic.members.add(m) PicnicUser.objects.get( user=request.user).picnics.add(picnic) n = Notification(message=request.user.username + " has joined your Picnic \"" + picnic.name + ".\"", \ picnicid=picnic.id) n.save() pUser = PicnicUser.objects.get(user=picnic.host) pUser.notifs.add(n) pUser.hasNotifications = True pUser.save() messages.success( request, f'You have successfully joined this Picnic!') return redirect('my-picnics') else: messages.warning( request, f'This Picnic is already full! Maximum of 15 people per Picnic.' ) return redirect('my-picnics') else: messages.warning( request, f'You have already joined this Picnic!') return redirect('my-picnics') if not picnic_exists: messages.warning( request, f'A picnic with that invite code does not exist!') return redirect('my-picnics') # username = form.cleaned_data.get('username') # messages.success(request, f'Your account has been created! You are now able to log in.') # return redirect('mypicnics') else: form = PicnicJoinForm() context = { 'small': True, 'title': 'My Picnics', 'modal': True, 'form': form, } return render(request, 'mypicnics/mypicnics.html', context)
def create_notification(self, user_id: int, amount: int, price: Decimal, order_of_name: str, received: bool): notification = Notification.order(user_id, amount, price, order_of_name, received) self.notifications.append(notification)
def set_notifications_attributes(user): setattr(user, 'notifications', user.notification_set.all().order_by('-created_at')[:20]) setattr(user, 'unseen_notifications', Notification.get_number_of_unseen_notifications(user=user)) return user
def notify_user(actor, action_obj, target, verb=''): notification = Notification(actor=actor, verb=verb, action_obj=action_obj, target=target) notification.save()