def notify_user(recipient, actor, verb, **kwargs): """ Handler function to create Notification instance upon action signal call. """ new_notification = Notification( recipient = recipient, actor_content_type=ContentType.objects.get_for_model(actor), actor_object_id=actor.pk, verb=text_type(verb), public=bool(kwargs.pop('public', False)), description=kwargs.pop('description', None), timestamp=kwargs.pop('timestamp', utc_now()), level=kwargs.pop('level', Notification.LEVELS.info), ) for opt in ('target', 'action_object'): obj = kwargs.pop(opt, None) if not obj is None: setattr(new_notification, '%s_object_id' % opt, obj.pk) setattr(new_notification, '%s_content_type' % opt, ContentType.objects.get_for_model(obj)) if len(kwargs) and EXTRA_DATA: new_notification.data = kwargs new_notification.save() return new_notification
def download_pdf(request): """ request download of PDF file - notify student of download """ results = {'success':False} if(request.method == u'POST'): try: POST = request.POST application = Application.objects.get(id=POST['application_id']) documents = application.documents.all() results['pdfs'] = [doc.url for doc in documents] results['success'] = True # notify user that application has been downloaded by company try: new_notification = Notification(user=application.user, company=application.company, receiver=1, notification=2) new_notification.save() except Exception, e: print e raise e except: pass json_results = simplejson.dumps(results) return HttpResponse(json_results, mimetype='application/json')
def add_topic(request, forum_id): '''Adds a new task to the department forum''' forum = get_object_or_404(Forum, pk=forum_id) topics = forum.topics.order_by('-updated').select_related() if request.method == 'POST': form=AddTopicForm(request.POST) if form.is_valid(): data=form.save(commit=False) data.forum=forum data.creator=request.user forum.topic_count+=1 data.save() body = '<span style="color:blue;">%s</span> started <span style="color:red;">%s</span> under <span style="color:green;">%s</span>' %(request.user.first_name,data.title,data.forum.title) link = '/forum/topic/%d/' %(data.id) notif = Notification(notif_body=body,link=link) notif.save() if data.forum.department == 'public': notif.is_public = True elif data.forum.department == 'coregroup': for user in Group.objects.get(name='Core').user_set.all(): notif.receive_users.add(user) else: notif.depts.add(Department.objects.get(name=data.forum.department)) notif.save() print notif.depts.all() forum.save() return redirect('forum.views.add_post',topic_id=data.pk) else: for error in form.errors: pass else: form=AddTopicForm() return render(request, 'forum/add_topic.html',{'form':form, 'forum': forum, 'topics': topics, })
def notify_handler(verb, **kwargs): """ Handler function to create Notification instance upon action signal call. """ kwargs.pop('signal', None) recipient = kwargs.pop('recipient') actor = kwargs.pop('sender') newnotify = Notification( recipient = recipient, actor_content_type=ContentType.objects.get_for_model(actor), actor_object_id=actor.pk, verb=unicode(verb), public=bool(kwargs.pop('public', True)), description=kwargs.pop('description', None), timestamp=kwargs.pop('timestamp', now()) ) for opt in ('target', 'action_object'): obj = kwargs.pop(opt, None) if not obj is None: setattr(newnotify, '%s_object_id' % opt, obj.pk) setattr(newnotify, '%s_content_type' % opt, ContentType.objects.get_for_model(obj)) if len(kwargs) and EXTRA_DATA: newnotify.data = kwargs newnotify.save()
def register_view(request): form = UserRegistrationForm(request.POST or None, request.FILES or None) if request.user.is_authenticated(): return redirect('login_view') if request.method == 'POST': if form.is_valid(): form.save() email = form.cleaned_data['email'] password = form.cleaned_data['password1'] activation_key = signing.dumps({'email': email}) user = User.objects.get(email=email) UserActivation.objects.filter(user=user).delete() new_activation = UserActivation(user=user, activation_key=activation_key, request_time=timezone.now()) new_activation.save() mailing.confirm_email(email, activation_key) notification = Notification(user=user, text='Пожалуйста, активируйте ваш профиль, перейдя по ссылке в письме на вашем почтовом ящике') notification.save() user = auth.authenticate(username=email, password=password) auth.login(request, user) return redirect('index_view') else: messages.warning(request, "Здесь есть неверно заполненные поля!") return render(request, 'reg.html', {'form': form}) return render(request, 'reg.html', {'form': form})
def follow(self, user): self.followed_users.add(user) self.add_redis_set.delay('followed_users', user.id) self.add_feeds_from_user.delay(user) user.add_redis_set.delay('followers', self.id) if user.notify_new_friend: note = Notification(sender=self, recipient=user, note_type=0, subject_id=self.id) note.save()
def create_chapter_notification(sender, instance, created, **kwargs): if created: notification = Notification() notification.user_id = instance.member_id notification.type = Notification.JOIN_CHAPTER notification.chapter_id = instance.chapter_id notification.save()
def create_award_notification(sender, instance, created, **kwargs): if created: notification = Notification() notification.user_id = instance.recipient_id notification.creator_id = instance.awarder_id notification.type = Notification.AWARD notification.award_id = instance.award_id notification.save()
def amo_notification(instance, **kw): """ Given an error see if we need to send a notification """ log('Firing signal: default_notification') user = User.objects.get(email__in=amo_users) if instance.domain in amo_domains: notification = Notification() notification.notifier = instance notification.save() notification.user.add(user)
def update_comment_list(sender, instance, created, **kwargs): if created: if instance.beat.creator.notify_comment: note = Notification() note.sender = instance.creator note.recipient = instance.beat.creator note.note_type = 1 note.content = instance.text[:20] note.subject_id = instance.beat_id note.save() redis_push_list('Beat', instance.beat_id, 'comments', instance.id)
def custom_notification(by,body,subject,superusers = True): if superusers: users = User.objects.filter(is_superuser=True) for user in users: context = {'user': user.name, 'body': body, 'subject': subject} emailit.api.send_mail(user.email, context, 'notification/emails/notification_email', from_email=user.email) notif = Notification(actor=by, recipient=user, verb=subject, description=body, emailed=True) notif.save() return True
def default_notification(instance, **kw): """ Given an error see if we need to send a notification """ log("Firing signal: default_notification") # todo, this will be changed to lookup a user profile as per # http://github.com/andymckay/arecibo/issues/issue/4 if instance.priority >= 5: return notification = Notification() notification.error = instance notification.user = [ str(u.key()) for u in approved_users() ] notification.save()
def page(request): if request.POST: if "cancel" in request.POST: return HttpResponseRedirect(reverse_lazy('index')) else: form = NewUserModel(request.POST) if form.is_valid(): name = form.cleaned_data['name'] surname = form.cleaned_data['surname'] email = form.cleaned_email() # TODO: all email on lower pas2 = form.cleaned_data['password2'] tel = form.cleaned_data['phone'] new_user = UserModel( email=email.lower(), is_active=True, name=name, surname=surname, phone=tel, messages=1) new_user.set_password(pas2) # TODO: play with commit False. # If captcha fails creates user anyways. try: taken = UserModel.objects.get(email=email.lower()) except UserModel.DoesNotExist: new_user.save() new_notification = Notification( user=new_user, notified=False, text=u"""Welcome to the website! You have an available account.""") new_notification.save() messages.success(request, 'New user created correctly.') # TODO: authenticate user otherwise next will always go to index if request.user.is_anonymous: return HttpResponseRedirect(reverse_lazy('index')) else: if request.user.is_admin: return HttpResponseRedirect(reverse_lazy('users_list')) else: return HttpResponseRedirect(reverse_lazy('panel')) else: return render( request, 'clients/user_create.html', {'form': form} ) else: form = NewUserModel() return render(request, 'clients/user_create.html', {'form': form})
def add_post(request, topic_id): topic = get_object_or_404(Topic, pk=topic_id) profile = get_object_or_404(UserProfile, pk=request.user.id) posts = topic.posts.all().select_related() #for i in posts: # This will truncates the description if it is greater than 100 characters and adds some dots #i.description = (i.description[:300] + " ....") if len(i.description) > 300 else i.description #i.description = i.description if request.method == 'POST': form=AddPostForm(request.POST) if form.is_valid(): profile.post_count+=1 profile.save() data=form.save(commit=False) data.user=request.user data.topic=topic data.save() body = '<span style="color:blue;">%s</span> posted in <span style="color:red;">%s</span> under <span style="color:green;">%s</span>' %(request.user.first_name,data.topic.title,data.topic.forum.title) link = '/forum/topic/%d/' %(data.topic.id) notif = Notification(notif_body=body,link=link) notif.save() if data.topic.forum.department == 'public': notif.is_public = True elif data.topic.forum.department == 'coregroup': print '-------------------' print 'coregroup' print '-------------------' for user in Group.objects.get(name='Core').user_set.all(): notif.receive_users.add(user) else: notif.receive_depts.add(Department.objects.get(name=data.topic.forum.department)) notif.save() print notif.receive_depts.all() topic.updated=datetime.datetime.now() topic.post_count+=1 topic.last_post=data topic.save() print topic.forum.pk forum = get_object_or_404(Forum, pk=topic.forum.pk) print forum forum.post_count+=1 forum.last_post=data forum.save() print data.pk return redirect('forum.views.show_topic', topic_id = topic.pk) else: for error in form.errors: messages.warning(request, error) else: form=AddPostForm() return render(request, 'forum/add.html',{ 'form':form, 'topic': topic, 'post_count': topic.post_count, 'posts': posts, })
def approve_user(request, approve_key): key = str(base64.b64decode(approve_key)) user = get_object_or_404(User, pk = int(key.split("_")[0])) group = get_object_or_404(GroupProfile, pk = int(key.split("_")[1])) try: user.groups.add(group.group) GroupPermission(group=group.group, user=user, permission_type=2).save() messages.add_message(request, messages.INFO, "Your approval is successful!") notification = Notification(text = \ "Manager of the group %s has just approved you to join.\n Click on the following link to go to that group: http://%s/group/%s/ \n \ Have fun!" % (group.group.name, get_domain(), group.slug), entity=group, recipient = user) notification.save() except: pass return HttpResponseRedirect('/')
def handle(self, *args, **options): today = date.today() to_notify = EmptyQuerySet() # Iterate over sales that are in effect for sale in Sale.objects.filter(start__lte=today, end__gte=today): # Find subscriptions that require the products on sale subscriptions = Subscription.objects.filter(product__in=sale.products.all()) # Remove subscriptions that have been notified subscriptions = subscriptions.exclude(notifications__sale=sale) to_notify |= subscriptions # Collect the subscriptions by user user_subs = defaultdict(list) for sub in to_notify: user_subs[sub.user].append(sub) from_email = getattr(settings, 'DEFAULT_FROM_EMAIL', '*****@*****.**') # Build the emails for user, subs in user_subs.iteritems(): to_email = user.email context = {'user': user, 'subscriptions': subs} subject = render_to_string('notifications/sale_subject.txt', context).replace('\n', '').strip() context['subject'] = subject text_content = render_to_string('notifications/sale_body.txt', context) html_content = render_to_string('notifications/sale_body.html', context) msg = EmailMultiAlternatives(subject, text_content, from_email, [to_email]) msg.attach_alternative(html_content, 'text/html') msg.send() # Will raise exceptions on failure # Mark all active sales for this product as notified for sub in subs: for sale in sub.product.active_sales.all(): notified = Notification() notified.sale = sale notified.subscription = sub notified.save()
def default_notification(instance, **kw): """ Given an error see if we need to send a notification """ log("Firing signal: default_notification") if instance.priority >= 5: return users = approved_users() if not users.count(): return notification = Notification() notification.notifier = instance notification.save() for user in users: notification.user.add(user)
def create_notification(type, source_id, from_user, for_user, message=None): notification = Notification(type=type, source_id=source_id, from_user=from_user, for_user=for_user, message=message, seen=False, action_taken=False) notification.save() extra = { "id": notification.id, "type": notification.type } app_key = settings.UA['app_key'] master_secret = settings.UA['master_secret'] logger.debug("app_key") logger.debug(app_key) logger.debug("master_secret") logger.debug(master_secret) airship = ua.Airship(app_key, master_secret) devices = for_user.user_devices.all() for device in devices: logger.debug("push_token") logger.debug(device.push_token) if device.push_token: push = airship.create_push() if device.device_type == 'iOS': push.audience = ua.device_token(device.push_token) elif device.device_type == 'Android': push.audience = ua.apid(device.push_token) push.notification = ua.notification(ios=ua.ios(alert=message, badge="+1", extra=extra), android=ua.android(alert=message, extra=extra)) push.device_types = ua.device_types('ios', 'android', ) logger.debug("push response") logger.debug(push.send()) return notification
def new_note(request, pk, format=None): """Create a new note for choice.""" choice = get_object_or_404(Choice, pk=pk) if request.user not in [choice.tutee, choice.tutor]: return HttpResponseRedirect(reverse('choices.views.requests')) if request.method == 'POST' and request.POST.get('content'): choice_note = ChoiceNote(choice=choice, content=request.POST.get('content'), user=request.user) choice_note.save() try: channel = Channel.objects.get(choice=choice) # Create notification for this channel notification = Notification() notification.action = 'new' notification.channel = channel notification.choice_note = choice_note notification.model = 'choice_note' notification.user = request.user notification.save() except Channel.DoesNotExist: pass if format and format == '.json': data = { 'choice_note': choice_note.to_json(), } elif request.is_ajax(): d = { 'choice': choice, 'choice_note': choice_note, } choice_note_template = loader.get_template( 'choices/choice_note.html') choice_note_form = loader.get_template( 'choices/choice_note_form.html') context = RequestContext(request, add_csrf(request, d)) data = { 'choice_note_template': choice_note_template.render( context), 'choice_note_form': choice_note_form.render(context) } if (format and format == '.json') or request.is_ajax(): return HttpResponse(json.dumps(data), mimetype='application/json') return HttpResponseRedirect(reverse('choices.views.detail', args=[choice.pk]))
def default_issue_notification(instance, **kw): """ Given an issue see default_issue_notification we need to send a notification """ log("Firing signal: default_notification") users = approved_users() if not users.count(): return notification = Notification() notification.type = "Issue" notification.type_key = str(instance.key()) notification.user = [ str(u.key()) for u in users ] notification.save() # turn this on when its all working #issue_created.connect(default_issue_notification, dispatch_uid="default_issue_notification") #issue_changed.connect(default_issue_notification, dispatch_uid="default_issue_notification")
def default_notification(instance, **kw): """ Given an error see if we need to send a notification """ log("Firing signal: default_notification") users = approved_users() filtered = [] for user in users: profile = get_profile(user) if profile.notification and instance.priority <= profile.notification: filtered.append(user) if not filtered: return notification = Notification() notification.type = "Error" notification.type_key = str(instance.key()) notification.user = [ str(u.key()) for u in filtered ] notification.save()
def sendNotification(timeframe, destiny, origin, href, message, custom_mail_message=None): notification = None timeout = timezone.now() - timeframe existing_notifications = Notification.objects.filter(destiny = destiny, origin = origin, href=href, notification=message, created_date__gt=timeout).order_by("-created_date") # if theres notifications inside the time frame, just update it if len(existing_notifications) >= 1: notification = existing_notifications[0] notification.created_date = timezone.now() notification.removed = False notification.read = False notification.read_date = None notification.save() else: # if theres no notification inside the time frame create a new one notification = Notification(destiny = destiny, origin = origin, href=href, notification=message) notification.save() if notification != None and notification.destiny.emif_profile.mail_not == True: subject = None message = None if custom_mail_message != None: (subject, message) = custom_mail_message else: subject = "EMIF Catalogue: Notification" message = """Dear %s,\n\n \n\n %s\n\n You can see it <a href="%s%s">here</a>. \n\nSincerely,\nEMIF Catalogue """ % (notification.destiny.get_full_name(), notification.notification, settings.BASE_URL ,notification.href) send_custom_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [notification.destiny.email])
def send_notification(self, users, message): #Send notifications notification = Notification( message=message ) notification.save() for user in users: receiver = Receivers( notification=notification, user=user, ) receiver.save() #Send email if users agreed with it if user.email_notifications: send_mail( 'New notification from Tracktool', notification.message, self.request.user.email, [user.email] )
def notify_people(request, key, species, obj, users, metadata=None): for user in users: if request and user == request.user: continue n = Notification(key=key, species=species, linked_object=obj, user=user) n.save() if metadata: n.set_metadata(metadata) n.save() try: notification_restriction, __ = NotificationRestriction.objects.get_or_create(user=user, key=key) except NotificationRestriction.MultipleObjectsReturned: NotificationRestriction.objects.filter(user=user, key=key).delete() notification_restriction, __ = NotificationRestriction.objects.get_or_create(user=user, key=key) notification_restriction_all, __ = NotificationRestriction.objects.get_or_create(user=user, key='') if notification_restriction.autoread or notification_restriction_all.autoread: n.seen = True n.save() if not notification_restriction.no_email and not notification_restriction_all.no_email and Notification.objects.filter(key=key, species=species, object_id=obj.pk, content_type=ContentType.objects.get_for_model(obj), user=user, seen=False).count() == 1: NotificationEmail(user=user, notification=n).save()
def actionsComment(request, post_id, pk): person_id = getPersonID(request) if type(person_id) is Response: return person_id if request.method == 'PUT': # Liking a comment comment = Comment.objects.get(pk=pk) if comment.comment_likes: if person_id in comment.comment_likes['persons']: comment.comment_likes['persons'].remove(person_id) else: comment.comment_likes['persons'].append(person_id) else: comment.comment_likes = dict(persons=[(person_id)]) comment.save() # make a notification to send if comment.person_id != person_id: notification = Notification(noti=2, person_for=comment.person_id, person_from=person_id, about=comment.post_id, created=datetime.now().timestamp()) notification.save() return Response(json.loads('{"action":"success"}'), status=status.HTTP_200_OK) elif request.method == 'DELETE': try: comment = Comment.objects.get(pk=pk) if comment.person_id == person_id: comment.delete() return Response(json.loads('{"action":"success"}'), status=status.HTTP_200_OK) except Comment.DoesNotExist: return Response(errorResponse(INVALID_REQUEST), status=status.HTTP_400_BAD_REQUEST) return Response(errorResponse(INVALID_REQUEST), status=status.HTTP_400_BAD_REQUEST)
def create_notifications(source, recipients, message, send_method='email', subject='GASTRONOM info'): """ Create and save notification objects to database :param source: str, name of app making notification :param recipients: list of class User objects :param subject: str, subject of notification :param message: str, body of notification message :param send_method: str, name of send method Examples: from django.contrib.auth.models import User from notifications.models import Notification from user_profile.models import UserProfile email to list of Users: Notification.create_notifications('notifications', recipients=[User.objects.get(id=1), User.objects.get(id=4)], message='This is my 100500th e-mail notification from Django.gastronom', send_method='email', subject='My 100500 message') telegram to list of Users: Notification.create_notifications('notifications', recipients=[User.objects.get(id=1), User.objects.get(id=4)], message='This is my 100500th e-mail notification from Django.gastronom', send_method='email', subject='My 100500 message') telegram to all Users: Notification.create_notifications('notifications', recipients=[user for user in User.objects.all()], message='Це моя перша телеграма from Django.gastronom', send_method='telegram') """ if send_method in send_methods: send_func = send_methods[send_method] for user in recipients: notification = Notification(source=source, recipient=user, subject=subject, message=message, send_method=send_method) notification.save() if USE_QUEUE: send_func.delay(notification.id) else: send_func(notification.id) else: logger.error('Invalid send method passed to the create_notifications')
def create_rank_notification(sender, instance, created, **kwargs): old_rank = instance.rank_tracker.changed().get('rank') if old_rank: notification = Notification() if old_rank < instance.rank_id: # promotion notification.type = Notification.PROMOTION if old_rank > instance.rank_id: # demotion notification.type = Notification.DEMOTION if instance.rank_id is None: # kicked notification.type = Notification.KICKED notification.user = instance notification.rank_id = instance.rank_id notification.save()
def post(request, query_id): user = request.user query = get_object_or_404(UserQuery, pk=query_id) serializer = MedicineSerializer(data=request.data, context={'request': request}) if serializer.is_valid(): #and user== query.taken_by: serializer.save(query=query) # else: # return Response(401) # for notification user = request.user title = user.first_name + " " + user.last_name + " prescribed you." message = query.title_problem notification = Notification(user=query.user, query=query, title=title, message=message) notification.save() return Response(MedicineSerializer(serializer.instance).data, status=201) return Response(serializer.errors, status=400)
def post(request): serializer = UserQuerySerializer(data=request.data, context={'request': request}) if serializer.is_valid(): user = request.user serializer.save(user=user) # for notification title = request.user.first_name + " " + request.user.last_name + " has asked you a question." message = request.data.get('title_problem') users = User.objects.filter( is_doctor=True, doctorprofile__speciality=request.data['tag']) query_id = serializer.data['id'] query = get_object_or_404(UserQuery, id=query_id) for doc_user in users: notification = Notification(user=doc_user, query=query, title=title, message=message) notification.save() return Response(UserQuerySerializer(serializer.instance).data, status=201) return Response(serializer.errors, status=400)
def add_notification(request): if request.method == "POST": form_data = JSONMiddleware() form_data.process_request(request) notification_instance = Notification() # if the user has failed to enter required form data return Key Error as error and status 500 try: notification_obj = NotificationType.objects.get(id=request.POST['notification_type']) notification_instance.notification_type = notification_obj notification_instance.notification_title = request.POST['notification_name'] notification_instance.notification_subject = request.POST['subject'] notification_instance.notification_body = request.POST['body'] print notification_instance except (ValueError, KeyError): return HttpResponse(json.dumps({'error':'Key Error'}), status=500) # if the user input data fails validation return Validation Error as error and status 500 try: notification_instance.full_clean() notification_instance.save() notification_contacts = request.POST.getlist('notification_contacts') notification_instance.notification_contacts.add(*notification_contacts) except ValidationError as error: return HttpResponse(json.dumps({'error':'Validation Error'}), status=500) return redirect('notification')
def register_confirm(request, activation_key): user_profile = UserActivation.objects.get(activation_key=activation_key) if not user_profile: # TODO: страница ошибки активации raise Exception("Неверный код") else: user_profile.confirm_time = timezone.now() user_profile.save() user = user_profile.user user.is_active = True user.save() notification = Notification(user=user, text='Вы успешно активировали аккаунт! Поздравляем вас со вступлением в сообщество спортсменов ;)') notification.save() if not request.user.is_authenticated(): user.backend = 'django.contrib.auth.backends.ModelBackend' auth.login(request, user) # TODO: page of success activation # TODO: send thanks-message on email return redirect('index_view')
def updatePaymentStatus_view(request, order_id): if not request.user.is_staff or not request.user.is_superuser or request.method != "POST": return HttpResponseRedirect('/404notfound/') try: order = Order.objects.get(order_id=order_id) if order.payment_status == True: order.payment_status = False notf = "Payment for your order #" + str(order.order_no) + " is pending." elif order.payment_status == False: order.payment_status = True notf = "Payment for your order #" + str(order.order_no) + " is accepted." order.save() except: messages.success(request, "Couldn't change payment status.") pass # SEND NOTIFICATION if order.account != None: notification = Notification() notification.account = order.account notification.content = notf notification.link = '/orders/' + order.order_id + '/' notification.save() return HttpResponseRedirect('/orders/management/')
def changepassword(request): if not request.user.is_authenticated: return redirect('login') template="changepassword.html" context={} if request.method=="POST": form=ChangePasswordForm(request.POST) if form.is_valid(): user=authenticate(request,username=request.user.username, password=form.cleaned_data["old_password"]) if user is not None: password=form.cleaned_data["new_password"] user.set_password(password) user.save() signin(request,user) messages.add_message(request,messages.SUCCESS, "Your password has been changed!") n=Notification(css="success", target=user.profile, expired=True, title='Password Changed', text='Your password on michaldackotutoring.co.uk has been changed!\n If you ever forget your password just contact me.') n.save() return redirect('profile') else: form.add_error(None, "Old password incorrect. Please try again.") else: form=ChangePasswordForm() context.update({"form":form}) return render(request,template,context)
def obj_update(self, bundle, **kwargs): """ Update application status and notes """ try: existing_application = Application.objects.get(id=int(kwargs['pk'])) if 'note' in bundle.data.keys(): existing_application.note = bundle.data['note'] existing_application.save() # send notification to student that his app has been viewed try: new_notification = Notification(user=existing_application.user, company=existing_application.company, receiver=1, notification=1) new_notification.save() except Exception, e: print e raise e if 'status' in bundle.data.keys(): # update application status existing_application.status = bundle.data['status'] if 'recruiter_email' in bundle.data.keys(): # update recruiter_email - email address existing_application.recruiter_email = bundle.data['recruiter_email'] if 'recruiter_message' in bundle.data.keys(): # update recruiter_message existing_application.recruiter_message = bundle.data['recruiter_message'] existing_application.save() # send notification to student that his status has been updated try: if bundle.data['status'] == 1 or bundle.data['status'] == 2: new_notification = Notification(user=existing_application.user, company=existing_application.company, receiver=1, notification=1) new_notification.save() if bundle.data['status'] == 3: new_notification = Notification(user=existing_application.user, company=existing_application.company, receiver=1, notification=3) new_notification.save() if bundle.data['status'] == 4: new_notification = Notification(user=existing_application.user, company=existing_application.company, receiver=1, notification=4) new_notification.save() except Exception, e: print e raise e
def notify_people(request, key, species, obj, users, metadata=None): for user in users: if request and user == request.user: continue n = Notification(key=key, species=species, linked_object=obj, user=user) n.save() if metadata: n.set_metadata(metadata) n.save() try: notification_restriction, __ = NotificationRestriction.objects.get_or_create( user=user, key=key) except NotificationRestriction.MultipleObjectsReturned: NotificationRestriction.objects.filter(user=user, key=key).delete() notification_restriction, __ = NotificationRestriction.objects.get_or_create( user=user, key=key) notification_restriction_all, __ = NotificationRestriction.objects.get_or_create( user=user, key='') if notification_restriction.autoread or notification_restriction_all.autoread: n.seen = True n.save() if not notification_restriction.no_email and not notification_restriction_all.no_email: # and Notification.objects.filter(key=key, species=species, object_id=obj.pk, content_type=ContentType.objects.get_for_model(obj), user=user, seen=False).count() == 1 NotificationEmail( user=user, notification=n, no_email_group=notification_restriction.no_email_group or notification_restriction_all.no_email_group).save()
def notification_create(request): if request.method == 'POST': try: user_pk = request.POST.get('user_pk', None) market_id = request.POST.get('market_id', None) details = request.POST.get('details', None) description = request.POST.get('description', None) comment = request.POST.get('comment', None) kind = request.POST.get('kind', None) notification_type = int(request.POST.get('type', 0)) valid_types = [6, 7, 8, 10] if notification_type not in valid_types: return JsonResponse({'message': 'invalid type'}, status=400) user = request.user role = get_role(user) if role not in ['corporate', 'finance'] or (role in ['corporate', 'finance'] and kind == 'consultant'): receiver = get_user_model().objects.get(pk=user_pk) elif kind == 'market': market = Market.objects.get(pk=market_id, is_active=True) else: return JsonResponse({'message': 'invalid kind'}, status=400) if notification_type == 6: """ Direct notification """ details = "From {}".format(user.person.get_full_name()) user = get_user_model().objects.get(pk=user_pk) mail_context = { 'details': details, 'comment': comment } subject = 'New notification' send_mail_wrapper( subject, 'notifications/emails/new_notification_email.html', mail_context, [user.person.email]) elif notification_type == 7: post_id = request.POST['post_id'] post = Post.objects.get(pk=post_id) details = "From {} about the bulletin {} ".format( user.person.get_full_name(), post.title ) elif notification_type == 8: registration_id = request.POST['registration_id'] registration = Registration.objects.prefetch_related('costumer').get(pk=registration_id) details = "From {} about the {} registration notes".format( user.person.get_full_name(), registration.costumer.get_full_name() ) elif notification_type == 10: details = "From corporate" notification = Notification() notification.creator = request.user notification.type = notification_type notification.description = description notification.details = details notification.comment = comment notification.save() if role not in ['corporate', 'finance'] or (role in ['corporate', 'finance'] and kind == 'consultant'): notification_receiver = NotificationReceiver() notification_receiver.receiver = receiver notification_receiver.notification = notification notification_receiver.save() elif kind == 'market': groups = ['supervisors', 'free agents', 'consultants', 'new markets coordinator'] excluded_groups = Group.objects.exclude(name__in=groups) user_ids = get_user_model().objects.filter( groups__name__in=groups, is_active=True, consultantprofile__market=market ).exclude( groups__in=excluded_groups ).distinct().values_list('id', flat=True) bulk_receiver_creation(notification, user_ids) return JsonResponse({}, status=200) except get_user_model().DoesNotExist: return JsonResponse({'user': '******'}, status=400) except Exception as e: return JsonResponse({}, status=500)
def newOrder_view(request): template_name = 'orders/confirmed-page.html' if request.method == "POST": cartKey = request.POST['cart'] phone = request.POST['cell'] order_type = request.POST['orderType'] account = None if request.user.is_authenticated: account = Account.objects.get(user=request.user) else: qs = Account.objects.filter(phone=phone).exists() if qs: account = Account.objects.get(phone=phone) order = Order() order.account = account try: cart = Cart.objects.get(key=cartKey) cart.is_active = True cart.save() order.cart = cart except: messages.warning(request, "Order request failed! Please try again.") return HttpResponseRedirect('/restaurants/' + cart.restaurant.slug + '/') _discount = 0.00 try: dObj = Discount.objects.get(key=request.POST['promoCode']) if dObj.used == False: _discount = int( float(cart.subtotal * dObj.percentage) / 100.00) dObj.used = True dObj.save() except: pass order.name = request.POST['name'] order.phone = phone order.shipping_address = request.POST['location'] order.order_type = order_type order.payment_method = request.POST['paymentMethod'] order.expected_time = request.POST['time'] if order_type == 'home': order.cost = cart.total - _discount + 30.00 # Shipping cost else: order.cost = cart.total - _discount order.discount = _discount messages.warning(request, "order is saved") order.save() # SEND NOTIFICATION if account != None: notification = Notification() notification.account = account notification.content = "You order <span class='font-weight-bold'>#" + str( order.order_no ) + "</span> has been added. We will confirm it in minutes." notification.link = '/orders/' + order.order_id + '/' notification.save() return HttpResponseRedirect('/orders/' + order.order_id + '/') messages.warning(request, "Something went wrong. Please try again.") return HttpResponseRedirect('/restaurants/' + cart.restaurant.slug + '/')
def view(request,id): if not request.user.is_authenticated: return redirect('login') profile= Profile.objects.get(user=request.user) try: session = Session.objects.get(id=id) except Session.DoesNotExist: messages.add_message(request,messages.ERROR, "Session does not exist!") return redirect('profile') if not profile == session.teacher.profile and not profile == session.student.profile and not profile == session.student.parent: messages.add_message(request,messages.ERROR, "This is not your session!") return redirect('profile') template="viewsession.html" if not request.method=="POST": sessionForm=ViewSessionForm() topicForm=AddTopicForm() uploadForm=UploadFileForm() if profile.isTeacher: session.changedForTeacher=False elif profile.isStudent: session.changedForStudent=False else: upload = Upload() uploadForm=UploadFileForm(request.POST, request.FILES, instance=upload) topic = Topic() topicForm=AddTopicForm(request.POST, instance=topic) s=Session.objects.get(id=session.id) sessionForm=ViewSessionForm(request.POST, instance=s) if uploadForm.is_valid() and not profile.isParent: upload = uploadForm.save() upload.save() session.uploads.add(upload) messages.add_message(request,messages.SUCCESS, "File uploaded!") target = Profile() if profile.isTeacher: target=session.student.profile session.changedForStudent=True else: target=session.teacher.profile session.changedForTeacher=True n=Notification( title='File Uploaded', text=profile.getName()+' has uploaded a file titled '+upload.name+' to a session on '+session.date.strftime("%d/%m/%Y at %H:%M")+'. Please have a look at it.', target=target, link="/school/session/"+str(id), css="warning" ) n.save() topicForm=AddTopicForm() sessionForm=ViewSessionForm() elif topicForm.is_valid() and profile.isTeacher: topic = topicForm.save() session.plannedTopics.add(topic) session.save() messages.add_message(request,messages.SUCCESS, topic.name+" added to session and subject!") uploadForm=UploadFileForm() sessionForm=ViewSessionForm() elif sessionForm.is_valid(): if not sessionForm.cleaned_data["plannedTopics"].first(): sessionForm.cleaned_data["plannedTopics"] = session.plannedTopics.all() notes = sessionForm.cleaned_data["notes"] req = sessionForm.cleaned_data["request"] feedback = sessionForm.cleaned_data["feedback"] report= sessionForm.cleaned_data["report"] plannedTopics=sessionForm.cleaned_data["plannedTopics"] learnedTopics=sessionForm.cleaned_data["learnedTopics"] if (session.notes!=notes) or (session.report!=report) or (session.request!=req) or (session.feedback!=feedback) or session.plannedTopics.all().exclude(id__in=plannedTopics.all()) or session.learnedTopics.all().exclude(id__in=learnedTopics.all()): if profile.isTeacher: session.changedForStudent=True n=Notification( title='Session Changed', text=profile.getName()+ ' has changed the session on '+session.date.strftime("%d/%m/%Y at %H:%M")+". Please review the changes they have made. "+ "If the session has not happened yet, please do this as soon as possible. If you have marked the session as complete, you will need to do this again after reviewing the most recent changes.", target=session.student.profile, link="/school/session/"+str(id), css="warning" ) n.save() elif profile.isStudent: session.changedForTeacher=True n=Notification( title='Session Changed', text=profile.getName()+ ' has changed the session on '+session.date.strftime("%d/%m/%Y at %H:%M")+". Please review the changes they have made. "+ "If the session has not happened yet, please do this as soon as possible. If you have marked the session as complete, you will need to do this again after reviewing the most recent changes.", target=session.teacher.profile, link="/school/session/"+str(id), css="warning" ) n.save() else: session.changedForTeacher=True session.changedForStudent=True n=Notification( title='Session Changed', text=profile.getName()+ ' has changed the session on '+session.date.strftime("%d/%m/%Y at %H:%M")+". Please review the changes they have made. "+ "If the session has not happened yet, please do this as soon as possible. If you have marked the session as complete, you will need to do this again after reviewing the most recent changes.", target=session.teacher.profile, link="/school/session/"+str(id), css="warning" ) n.save() n=Notification( title='Session Changed', text=profile.getName()+ ' has changed the session on '+session.date.strftime("%d/%m/%Y at %H:%M")+". Please review the changes they have made. "+ "If the session has not happened yet, please do this as soon as possible. If you have marked the session as complete, you will need to do this again after reviewing the most recent changes.", target=session.student.profile, link="/school/session/"+str(id), css="warning" ) n.save() messages.add_message(request,messages.SUCCESS, "Session updated!") print("here") session = sessionForm.save() uploadForm=UploadFileForm() topicForm=AddTopicForm() context={"session":session} if not session.done: topics = Topic.objects.filter(subject__in=session.subjects.all()).exclude(id__in=session.plannedTopics.all()) else: topics = session.plannedTopics.all().exclude(id__in=session.learnedTopics.all()) context.update({"sessionForm":sessionForm,"topicForm":topicForm, "uploadForm":uploadForm, "topics":topics}) session.save() return render(request,template,context)
def write(request): if request.method == 'POST': # get form data subject = request.POST.get('subject') single = request.POST.get('single') to_customers = request.POST.get('toCustomer', 0) to_suppliers = request.POST.get('toSupplier', 0) email_list = json.loads(request.POST.get('emailList')) body = request.POST.get('body') # send notification/emails if single: try: user = Supplier.objects.get(email=single) context = {'user': user.name, 'body': body, 'subject': subject} emailit.api.send_mail(user.email, context, 'notification/emails/notification_email', from_email=request.user.email) notif = Notification(actor=request.user, recipient=request.user, verb=subject, description=body, emailed=True) notif.save() except: # user = Supplier.objects.get(email=single) context = {'user': single, 'body': body, 'subject': subject} emailit.api.send_mail(single, context, 'notification/emails/notification_email', from_email=request.user.email) notif = Notification(actor=request.user, recipient=request.user, verb=subject, description=body, emailed=True) notif.save() return HttpResponse('success') for email in email_list: user = User.objects.get(email=email) if user.send_mail: context = {'user': user.name, 'body': body, 'subject': subject} emailit.api.send_mail(user.email, context, 'notification/emails/notification_email', from_email=request.user.email) notif = Notification(actor=request.user, recipient=user, verb=subject, description=body, emailed=True) notif.save() else: notify.send(request.user, recipient=user, verb=subject, description=body) # check for bulk group mailing/notification if 1 == int(to_customers): customers = Customer.objects.all() for customer in customers: context = { 'user': customer.name, 'body': body, 'subject': subject } emailit.api.send_mail(customer.email, context, 'notification/emails/notification_email', from_email=request.user.email) notif = Notification(actor=request.user, recipient=customer, verb=subject, description=body, emailed=True) notif.save() if 1 == int(to_suppliers): suppliers = Supplier.objects.all() for supplier in suppliers: context = { 'user': supplier.name, 'body': body, 'subject': subject } emailit.api.send_mail(supplier.email, context, 'notification/emails/notification_email', from_email=request.user.email) notif = Notification(actor=request.user, recipient=supplier, verb=subject, description=body, emailed=True) notif.save() HttpResponse(email_list) ctx = { 'users': User.objects.all().order_by('-id'), 'templates': EmailTemplate.objects.all().order_by('-id') } if request.method == 'GET': if request.GET.get('pk'): try: product = ProductVariant.objects.get( pk=int(request.GET.get('pk'))) ctx = { 'product': product, 'users': User.objects.all().order_by('-id'), 'templates': EmailTemplate.objects.all().order_by('-id') } return TemplateResponse( request, 'dashboard/notification/write_single.html', ctx) except Exception, e: return HttpResponse(e)
def push_notification(template, category, web_onclick_url='', android_onclick_activity='', ios_onclick_action='', is_personalised=False, person=None, has_custom_users_target=False, persons=None, send_only_to_subscribed_users=False): """ Unified method to generate notification object and execute pushing :param template: Template string or Body string of the notification :param category: Category object to which the notification belongs to :param web_onclick_url: Onclick url for web push notification as well as at frontend :param android_onclick_activity: Name of android activity to open on clicking the notification :param ios_onclick_action: # TODO :param is_personalised: Flag for a personalised notification :param person: Person (id/instance) corresponding to the personalised notification :param has_custom_users_target: Flag for a notification with a custom users target :param persons: Custom users (person's instance/id) target :param send_only_to_subscribed_users: Flag for a notification only to be sent to subscribed users :return: Notification object """ try: app_base_url = category.app_config.base_urls.http except AttributeError: app_base_url = '' notification = Notification( template=template, category=category, web_onclick_url=web_onclick_url or app_base_url, android_onclick_activity=android_onclick_activity, ios_onclick_action=ios_onclick_action, is_personalised=is_personalised, has_custom_users_target=has_custom_users_target, ) # Exception handling if is_personalised and has_custom_users_target: raise ValueError( '\'is_personalised\' and \'has_custom_users_target\' cannot be ' 'True at the same time ') if is_personalised: if person is None: logger.error( f'Incorrect argument for notification #{notification.id}: ' '\'person\' cannot be None for a personalised notification') raise ValueError( '\'person\' cannot be None for a personalised notification') else: if isinstance(person, Person): person = person.id notification.save() all_endpoints = PushEndpoint.fetch(person) UserNotification(person_id=person, notification_id=notification.id).push() if all_endpoints: _ = fcm_push( notification_id=notification.id, tokens=all_endpoints, ) logger.info( f'Personal notification #{notification.id} successfully sent') return notification if has_custom_users_target: if persons is None: logger.error( 'Incorrect argument for notification #{notification.id}: ' '\'persons\' cannot be None while \'has_custom_users_target\' ' 'is True ') raise ValueError( '\'persons\' cannot be None while \'has_custom_users_target\' ' 'is True ') else: persons = [ person.id if isinstance(person, Person) else person for person in persons ] if send_only_to_subscribed_users: # Get a set of all subscribed people ids subscribed_persons = { int(person_id) for person_id in Subscription.fetch_people( category_slug=category.slug, action='notifications') } # Grab an intersection of the subscribed people and the complete list persons = list(subscribed_persons.intersection(persons)) notification.save() _ = execute_users_set_push(notification_id=notification.id, persons=persons) logger.info(f'Mass notification #{notification.id} successfully sent') return notification if not (is_personalised and has_custom_users_target): notification.save() _ = execute_topic_push(notification) logger.info(f'Topic notification #{notification.id} successfully sent') return notification
def init_new_user(user_id): # 初始化新用户信息 calendar_obj = Calendar.objects.get(slug="default") # 绑定学员 健身小助手 user_obj = get_user_model().objects.get(id=user_id) helper_obj = get_user_model().objects.get(username="******") if user_obj.profile.u_type == 1: # 如果用户是教练,添加小助手为学员 coach_user = user_obj member_user = helper_obj else: coach_user = helper_obj member_user = user_obj CoachMemberRef(member=member_user.member, coach=coach_user.coach).save() # 创建 把课程时间&课程动作记录&健身记录 时间为本周末 today = datetime.datetime.today() start = today.replace(hour=14, minute=0, second=0) end = today.replace(hour=15, minute=0, second=0) event_queryset = Event.objects.filter(user=member_user, start=start) month_ago = today - datetime.timedelta(days=30) Event.objects.filter(ctime__lt=month_ago).delete() if not event_queryset: new_event = Event(coach=coach_user, user=member_user, start=start, end=end, description="示例数据,可删除", calendar=calendar_obj, color_event="#f4f4f4") new_event.save() else: new_event = event_queryset[0] try: new_course = PurchaseCourse(user=member_user, amount=1, remain=1) new_course.save() except IntegrityError: pass ExerciseRecord.objects.filter(user=helper_obj).delete() for i in range(7): temp_id = random.randint(0, 340) try: exercise_obj = FitnessExercise.objects.get(id=temp_id) new_exc_record = ExerciseRecord(event=new_event, user=member_user, exercise=exercise_obj, value=10, number=15) new_exc_record.save() except FitnessExercise.DoesNotExist: pass lose_goal, _ = FitGoal.objects.get_or_create(name="健身减脂", user=member_user, defaults={ "desc": "目标示例数据,可删除", "measure": "KG", "goal": 60 }) body_goal, _ = FitGoal.objects.get_or_create(name="增肌塑形", user=member_user, defaults={ "desc": "目标:腹部肌肉明显,可删除", "measure": "体脂率", "goal": 10 }) arm_goal, _ = FitGoal.objects.get_or_create(name="手臂围度", user=member_user, defaults={ "desc": "目标:手臂肌肉围度增加,可删除", "measure": "CM", "goal": 40 }) GoalRecord.objects.filter(user=helper_obj).delete() for goal_obj in [lose_goal, body_goal, arm_goal]: for i in [7, 6, 5, 4, 3, 2, 1]: temp_date = today - datetime.timedelta(days=i) new_goal_record = GoalRecord(fit_goal=goal_obj, user=member_user, current=goal_obj.goal + i, cdate=temp_date) new_goal_record.save() # 添加一条新消息 new_notify = Notification( recipient=user_obj, sender=helper_obj, action_object_content_type=ContentType.objects.get_for_model( calendar_obj), action_object_id=calendar_obj.pk, title="欢迎加入Fitahol,竭诚为您服务。", description="系统陆续更新中,有任何意见欢迎您通过微信公众号 meta-fitness 告诉我们。", show_time=new_event.ctime) new_notify.save()
def add_vehicle(request): if request.method == 'POST': reg = request.POST['reg'] lot = request.POST['lot'] time = request.POST['time'] time = int(time) hrs = int(request.POST['hrs']) mins = int(request.POST['mins']) error_vehicle_exists = False added = False notification_pushed = False added_to_record = False slot = Slot.objects.filter(pk=lot)[0] if Customer.objects.filter(Q(vehicle_reg_no=reg) & Q(is_active=True)).count() > 0: error_vehicle_exists = True elif not slot.occupied: customer = Customer(vehicle_reg_no=reg, slot=slot, alloted_minutes=time) customer.save() slot.occupied = True slot.save() added = True strTime = '' if hrs == 0: strTime = f'{mins} mins' else: strTime = f'{hrs} hrs {mins} mins' notifContent = f'{strTime} up for {reg} - Slot {slot.slot_num} ({Slot.SLOT_TYPES[slot.slot_type-1][1]})' notif = Notification(content=notifContent, slot_id=slot.id, customer_id=customer.id) notif.save() notification_pushed = True customer.notification_id = notif.id customer.save() # un-comment for using celery # push notification to celery # minutes = time # show_notification.apply_async((notif.id, 0), eta=datetime.now() + timedelta(minutes=minutes)) # create today's record if it does not exist todaysRecord = DailyRecord.objects.filter(date=date.today()) if todaysRecord.count() == 0: todaysRecord = DailyRecord() todaysRecord.save() else: todaysRecord = todaysRecord[0] todaysRecord.customers.add(customer) # add customer to today's record data = { 'error_vehicle_exists': error_vehicle_exists, 'added': added, 'notification_pushed': notification_pushed, 'added_to_record': added_to_record, } return JsonResponse(data)
def follow(request, pk): user = request.user to_user = get_object_or_404(User, pk=pk) url = request.META.get('HTTP_REFERER') read_marks = BookMark.objects.filter( user=to_user, mark_status='r_ed').order_by('-updated_at') reading_marks = BookMark.objects.filter( user=to_user, mark_status='r_ing').order_by('-updated_at') fa_marks = BookMark.objects.filter(user=to_user, fa_status='fa') books = Book.objects.all() read_list = [] reading_list = [] fa_list = [] for read_mark in read_marks: data = { 'read_mark': read_mark, 'read_book': books.get(id=read_mark.book_id) } read_list.append(data) for reading_mark in reading_marks: data = { 'reading_mark': reading_mark, 'reading_book': books.get(id=reading_mark.book_id) } reading_list.append(data) for fa_mark in fa_marks: data = {'fa_mark': fa_mark, 'fa_book': books.get(id=fa_mark.book_id)} fa_list.append(data) if request.method == 'POST' and user != to_user: try: followed = Follow.objects.get(follower=user, following=to_user) followed.delete() except: follow = Follow(follower=user, following=to_user) follow.save() notify = Notification(sender=user, user=to_user, notification_type=2) notify.save() activity = Activity(user=user, activity_type='fo', activity=follow) activity.save() return HttpResponseRedirect(url) else: if request.method == 'GET': user = request.user to_user = get_object_or_404(User, pk=pk) num_following = Follow.objects.filter(follower=to_user).count() num_follower = Follow.objects.filter(following=to_user).count() try: followed = Follow.objects.get(follower=user, following=to_user) is_follower = 1 except: is_follower = 0 context = { 'user': user, 'to_user': to_user, 'following': num_following, 'follower': num_follower, 'read_list': read_list, 'reading_list': reading_list, 'fa_list': fa_list, 'is_followed': is_follower } return render(request, 'users/user_profile.html', context=context) else: return redirect('UserProfile')
def add_heart(self, user): self.hearts.add(user) self.add_redis_set('hearts', user.id) if self.creator.notify_heart: note = Notification(sender=user, recipient=self.creator, note_type=2, subject_id=self.id) note.save()
def write(request): if request.method == 'POST': # get form data subject = request.POST.get('subject') single = request.POST.get('single'); to_customers = request.POST.get('toCustomer',0) to_suppliers = request.POST.get('toSupplier',0) email_list = json.loads(request.POST.get('emailList')) body = request.POST.get('body') # send notification/emails if single: try: user = Supplier.objects.get(email=single) context = {'user': user.name, 'body': body, 'subject': subject} emailit.api.send_mail(user.email, context, 'notification/emails/notification_email', from_email=request.user.email) notif = Notification(actor=request.user, recipient=request.user, verb=subject, description=body, emailed=True) notif.save() except: #user = Supplier.objects.get(email=single) context = {'user': single, 'body': body, 'subject': subject} emailit.api.send_mail(single, context, 'notification/emails/notification_email', from_email=request.user.email) notif = Notification(actor=request.user, recipient=request.user, verb=subject, description=body, emailed=True) notif.save() return HttpResponse('success') for email in email_list: user = User.objects.get(email=email) if user.send_mail: context = {'user': user.name, 'body': body, 'subject': subject} emailit.api.send_mail(user.email, context, 'notification/emails/notification_email', from_email=request.user.email) notif = Notification(actor=request.user, recipient=user, verb=subject, description=body, emailed=True) notif.save() else: notify.send(request.user, recipient=user, verb=subject, description=body) # check for bulk group mailing/notification if 1 == int(to_customers): customers = Customer.objects.all() for customer in customers: context = {'user': customer.name, 'body': body, 'subject': subject} emailit.api.send_mail(customer.email, context, 'notification/emails/notification_email', from_email=request.user.email) notif = Notification(actor=request.user, recipient=customer, verb=subject, description=body, emailed=True) notif.save() if 1 == int(to_suppliers): suppliers = Supplier.objects.all() for supplier in suppliers: context = {'user': supplier.name, 'body': body, 'subject': subject} emailit.api.send_mail(supplier.email, context, 'notification/emails/notification_email', from_email=request.user.email) notif = Notification(actor=request.user, recipient=supplier, verb=subject, description=body, emailed=True) notif.save() HttpResponse(email_list) ctx = { 'users':User.objects.all().order_by('-id'), 'templates':EmailTemplate.objects.all().order_by('-id') } if request.method == 'GET': if request.GET.get('pk'): try: product = ProductVariant.objects.get(pk=int(request.GET.get('pk'))) ctx = { 'product':product, 'users':User.objects.all().order_by('-id'), 'templates':EmailTemplate.objects.all().order_by('-id') } return TemplateResponse(request, 'dashboard/notification/write_single.html', ctx) except Exception, e: return HttpResponse(e)
share_pending.user_invite = request.user share_pending.save() success_msg = "An invitation has been sent to your co-worker start collaboration in your database. If you need further assistance, please do not hesitate to contact EMIF Catalogue team." link_activation = settings.BASE_URL + "share/activation/" + share_pending.activation_code new_notification = Notification( destiny=username_to_share, origin=request.user, notification=( fingerprint.findName() + " has been shared with you, please click here to activate it."), type=Notification.SYSTEM, href=link_activation) new_notification.save() emails_to_feedback = [] #print settings.ADMINS for k, v in settings.ADMINS: emails_to_feedback.append(v) try: message = """%s Now you're able to edit and manage the database. \n\n To activate the database in your account, please open this link: %s \n\nSincerely,\nEMIF Catalogue """ % (message, link_activation)
def user_follow(sender, instance, *args, **kwargs): follow = instance sender = follow.follower following = follow.following notify = Notification(sender=sender, user=following, notification_type=3) notify.save()
else: share_pending = SharePending() share_pending.user = username_to_share share_pending.db_id = db_id share_pending.activation_code = generate_hash() share_pending.pending = True share_pending.user_invite = request.user share_pending.save() success_msg = "An invitation has been sent to your co-worker start collaboration in your database. If you need further assistance, please do not hesitate to contact EMIF Catalogue team." link_activation = settings.BASE_URL + "share/activation/"+share_pending.activation_code new_notification = Notification(destiny=username_to_share ,origin=request.user, notification=(fingerprint.findName()+" has been shared with you, please click here to activate it."), type=Notification.SYSTEM, href=link_activation) new_notification.save() emails_to_feedback = [] #print settings.ADMINS for k, v in settings.ADMINS: emails_to_feedback.append(v) try: message = """%s Now you're able to edit and manage the database. \n\n To activate the database in your account, please open this link: %s \n\nSincerely,\nEMIF Catalogue """ % (message,link_activation)
def edit(request, groupid): group = Group.objects.get(id=groupid) if request.user.is_authenticated: request.user.profile.last_online_update() if request.user in group.editors.all() or request.user == group.admin: if request.POST.get('type') == 'allowarticle': article = BasicArticle.objects.get(id=request.POST.get('data')).get_child() if article.__class__.__name__ != "PersonalArticle" and article.group == group: article.allowed = True article.save() if article.__class__.__name__ == "PersonalInCommunityArticle": if article.author.profile.notificationsettings.post_published_notifications: notifications.create_notification_post_published(group, article.author, 'post_accepted') return HttpResponse('Ok') elif request.POST.get('type') == 'deletearticle': article = BasicArticle.objects.get(id=request.POST.get('data')).get_child() if article.__class__.__name__ != "PersonalArticle" and article.group == group: if article.__class__.__name__ == "PersonalInCommunityArticle": if article.author.profile.notificationsettings.post_published_notifications: notifications.create_notification_post_published(group, article.author, 'post_accepted') article.delete() return HttpResponse('Ok') elif request.POST.get('type') == 'getpost': article = BasicArticle.objects.get(id=request.POST.get('data')) return HttpResponse(article.text) elif request.POST.get('type') == 'deletepost': article = BasicArticle.objects.get(id=request.POST.get('data')) if request.user != article.author and not article.author is None: try: notification_text = "Ваш пост в " + group.groupname + " удален" notification_name = "Пост удален" notification_href = '/groups/' + group.slug + '/' notification = Notification(not_text=notification_text, not_name=notification_name, not_link=notification_href, not_date=datetime.now()) notification.save() notificationlist = Notificationlist.objects.get(user=article.author).notifications notificationlist.add(notification) except: print('Notification Error') article.delete() return HttpResponse('Ok') if request.POST.get('type') == 'delete_from_collection': # print(request.POST.get('file')) try: groupfile = group.files.get(id=request.POST.get('file')) groupfile.delete() except: pass return HttpResponse('Ok') if request.POST.get('type') == 'delete_request_article': article = BasicArticle.objects.get(id=request.POST.get('data')) article.delete() return HttpResponse('Ok') elif request.POST.get('type') == 'plus' or request.POST.get('type') == 'plusplus': basic_article = BasicArticle.objects.get(id=request.POST.get('articleid')) if basic_article: basic_article.plus(request.user) elif request.POST.get('type') == 'remove_plus': basic_article = BasicArticle.objects.get(id=request.POST.get('articleid')) if basic_article: basic_article.remove_plus(request.user) elif request.POST.get('type') == 'minus' or request.POST.get('type') == 'minusminus': basic_article = BasicArticle.objects.get(id=request.POST.get('articleid')) if basic_article: basic_article.minus(request.user) elif request.POST.get('type') == 'remove_minus': basic_article = BasicArticle.objects.get(id=request.POST.get('articleid')) if basic_article: basic_article.remove_minus(request.user) if request.POST.get('type') == 'delete_from_collection' and not os.path.isfile(request.POST.get('file')): # print(request.POST.get('file')) try: groupfile = group.files.get(id=request.POST.get('file')) groupfile.delete() except: pass return HttpResponse('Ok') return HttpResponse('error0')
def obj_update(self, bundle, **kwargs): """ Update application status and notes """ try: existing_application = Application.objects.get( id=int(kwargs['pk'])) if 'note' in bundle.data.keys(): existing_application.note = bundle.data['note'] existing_application.save() # send notification to student that his app has been viewed try: new_notification = Notification( user=existing_application.user, company=existing_application.company, receiver=1, notification=1) new_notification.save() except Exception, e: print e raise e if 'status' in bundle.data.keys(): # update application status existing_application.status = bundle.data['status'] if 'recruiter_email' in bundle.data.keys(): # update recruiter_email - email address existing_application.recruiter_email = bundle.data[ 'recruiter_email'] if 'recruiter_message' in bundle.data.keys(): # update recruiter_message existing_application.recruiter_message = bundle.data[ 'recruiter_message'] existing_application.save() # send notification to student that his status has been updated try: if bundle.data['status'] == 1 or bundle.data['status'] == 2: new_notification = Notification( user=existing_application.user, company=existing_application.company, receiver=1, notification=1) new_notification.save() if bundle.data['status'] == 3: new_notification = Notification( user=existing_application.user, company=existing_application.company, receiver=1, notification=3) new_notification.save() if bundle.data['status'] == 4: new_notification = Notification( user=existing_application.user, company=existing_application.company, receiver=1, notification=4) new_notification.save() except Exception, e: print e raise e
def QuizSubmitView(request, course_slug, lesson_slug): if request.method == 'POST': course = Course.objects.get(slug=course_slug) lesson = Lesson.objects.get(slug=lesson_slug) quiz = Quiz.objects.get(lesson__slug=lesson.slug) quizquestionanswers = Question.objects.filter( quiz__title=quiz.title)[:10] quizscore = 0 quizform = request.POST.copy() processedquiz = {} for quizquestionanswer in quizquestionanswers: processedquiz[f'q{quizquestionanswer.id}'] = quizform[ f'q{quizquestionanswer.id}'] if processedquiz[ f'q{quizquestionanswer.id}'] == quizquestionanswer.answer: quizscore += 1 else: quizscore += 0 try: quizparticipation = QuizParticipation.objects.get( quiz__title=quiz.title, participator__username=request.user.username) if quizparticipation: print(quizparticipation) schedule_next = quizparticipation.participate_next - \ datetime.datetime.now(tz=timezone.utc) if schedule_next.days > 7: quizparticipation.quiz = quiz quizparticipation.quiz_score = quizscore quizparticipation.participate_date = datetime.datetime.now( tz=timezone.utc) quizparticipation.participate_next = datetime.datetime.now(tz=timezone.utc) + \ datetime.timedelta(days=7) quizparticipation.save() messages.success(request, 'Thank you for your reparticipation') notification = Notification() notification.title = f'Thankyou for your participation in { quiz.title }' notification.message = f'You scored: {quizparticipation.quiz_score}. You can participate after {quizparticipation.participate_next}' notification.user = request.user notification.save() return redirect('courses:lesson-detail', course_slug, lesson_slug) else: messages.success(request, 'You can not retake within 7 days') return redirect('courses:lesson-detail', course_slug, lesson_slug) except: quizparticipation = QuizParticipation() quizparticipation.quiz = quiz quizparticipation.quiz_score = quizscore quizparticipation.participate_date = datetime.datetime.now( tz=timezone.utc) quizparticipation.participate_next = datetime.datetime.now(tz=timezone.utc) + \ datetime.timedelta(days=7) quizparticipation.participator = request.user quizparticipation.save() messages.success(request, 'Thank you for your participation') notification = Notification() notification.title = f'Thankyou for your participation in { quiz.title }' notification.message = f'You scored: {quizparticipation.quiz_score}. You can participate after {quizparticipation.participate_next}' notification.user = request.user notification.save() return redirect('courses:lesson-detail', course_slug, lesson_slug)
def user_liked_post(sender, instance, *args, **kwargs): like = instance post = like.post sender = like.user notify = Notification(post=post, sender=sender, user=post.user, notification_type=1) notify.save()
def create(self, request, *args, **kwargs): linked_content_object = None if 'linked_content_object' in request.data: linked_content_object = request.data['linked_content_object'] del request.data['linked_content_object'] response = super(PostViewset, self).create(request, *args, **kwargs) post = Post.objects.get(pk=response.data['id']) if post.post_type == 2 or post.post_type == 3: link = Link.objects.create(data=linked_content_object, created_by=post.created_by, modified_by=post.modified_by) post.linked_content_type = ContentType.objects.get( app_label="links", model="link") post.linked_object_id = link.pk post.save() if post.post_type == 4: if 'image' in linked_content_object: if len(linked_content_object['image']) > 0: if re.compile('^data:image/jpeg;').match( linked_content_object['image']) is not None: type = 'image/jpeg' if re.compile('^data:image/png;').match( linked_content_object['image']) is not None: type = 'image/png' # TODO: retrieve image if exists as binary data image_data = binascii.a2b_base64( linked_content_object['image'].replace( 'data:' + type + ';base64,', '')) temp_file = NamedTemporaryFile(delete=False) temp_file.close() f = open(temp_file.name, mode='wb') f.write(image_data) f.close() f = open(temp_file.name, mode='rb') pil_image = Image.open(f) uploaded_file = UploadedFile(file=f, name='%s.jpg' % post.id, content_type=type, size=len(image_data)) client = boto3.client( 'rekognition', region_name='us-east-1', aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY) rekog_response = client.detect_faces(Image={ 'Bytes': image_data, }, Attributes=['ALL']) display_position = 'center' face_data = None if 'FaceDetails' in rekog_response: if len(rekog_response['FaceDetails']) > 0: if rekog_response['FaceDetails'][0]['BoundingBox'][ 'Top'] < .33: display_position = 'top' elif rekog_response['FaceDetails'][0][ 'BoundingBox']['Top'] > .6: display_position = 'bottom' face_data = rekog_response['FaceDetails'] average_color = average_image_color(pil_image) color = "rgb(%s,%s,%s)" % (average_color['R'], average_color['G'], average_color['B']) image = ImageObject.objects.create( image=uploaded_file, width=pil_image.width, height=pil_image.height, created_by=post.created_by, modified_by=post.modified_by, display_position=display_position, face_data=face_data, color=color) post.linked_content_type = ContentType.objects.get( app_label="images", model="image") post.linked_object_id = image.pk post.save() f.close() temp_file.close() os.remove(temp_file.name) if post.parent_post is None: payload = { "post_id": str(post.id), "created_by_id": str(post.created_by_id), "image": post.created_by.get_profile_image_cache_url(), "type": NOTIFICATION_TYPES.NEW_POST } r = PushNotificationRequest() r.create({ "send_to_all": True, # "tokens": ['fgKJr4Br_9Y:APA91bHjLX10CFRcaVQ-ehRPHJxocSRJ7UvRlN62A_GrjzaHass6dEgG1CdllXDFxq4N1xahWSPD6lMubd14bh3cVuRNt-oonwLLAW5-1HHDish-BcRGd_dcpB1eGzIcPt7uLaxCPXc8'], "notification": { "message": "%s" % str(post.text_content), "title": "%s made a post" % post.created_by, "payload": payload, "ios": { "badge": "1", "sound": "", "priority": 10 }, "android": { "sound": "", "priority": "high" } }, "profile": IONIC_PUSH_GROUP }) if post.parent_post: tokens_for_parent_post_creator_qs = PushToken.objects.filter( user=post.parent_post.created_by, push_group=IONIC_PUSH_GROUP, is_active=True).values_list('token').exclude( user=post.created_by_id) tokens_for_parent_post_creator = list() for token in tokens_for_parent_post_creator_qs: tokens_for_parent_post_creator.append(token[0]) payload = { "comment_id": str(post.id), "image": post.created_by.get_profile_image_cache_url(), "post_id": str(post.parent_post_id), "created_by_id": str(post.created_by_id), "type": NOTIFICATION_TYPES.NEW_COMMENT } title = "%s commented on your post." % str(post.created_by) message = "%s" % post.text_content if post.parent_post.created_by_id != request.user.id: notif = Notification(to_user=post.parent_post.created_by, from_user=post.created_by, created_on=timezone.datetime.now(), title=title, message=message, payload=payload) notif.save() if len(tokens_for_parent_post_creator) > 0: r = PushNotificationRequest() r.create({ "tokens": list(tokens_for_parent_post_creator), "notification": { "message": message, "title": title, "payload": payload, "ios": { "badge": "1", "sound": "default", "priority": 10 }, "android": { "sound": "default", "priority": "high" } }, "profile": IONIC_PUSH_GROUP }) return Response(PostSerializer(post).data)
def dashboard(request): user=request.user traveller_user=get_object_or_404(Traveller, email=user) bio = traveller_user.bio.split('.',5) bio_first = ". ".join(bio[:5])+(".") traveller_reviews = Traveller_Review.objects.all().filter(traveller=traveller_user) guide_user = Guide.objects.all().filter(email=user).first() guide_reviews = Guide_Review.objects.all().filter(guide=user) notifications = Notification.objects.all().filter(receiver_email=user).order_by('-reg_date') trip_notifications = Trip_Notification.objects.all().filter(receiver_email=user) guide_historys = History.objects.all().filter(guide=user,tour_complete=True) traveller_historys = History.objects.all().filter(traveller=user,tour_complete=True) ongoing_guide_tours = History.objects.all().filter(guide=user,tour_initiated=True) ongoing_traveller_tours = History.objects.all().filter(traveller=user,tour_initiated=True) if traveller_user.is_guide: guide_user1 = get_object_or_404(Guide, email=user) if guide_user1: trip_notifications = Trip_Notification.objects.all().filter(sender_email=user) else: trip_notifications = Trip_Notification.objects.all().filter(receiver_email=user) places = Place.objects.all() place_pattern='' for place in places: place_pattern = place.name+'|'+place_pattern context = { 'traveller_user':traveller_user, 'my_profile':True, 'logged_in_user':traveller_user, #logged_in_user is for avatar in navbar 'guide_user' : guide_user, 'notifications': notifications, 'trip_notifications': trip_notifications, 'bio_first': bio_first, 'places' : places, 'place_pattern' : place_pattern, 'guide_reviews': guide_reviews, 'guide_historys': guide_historys, 'traveller_historys': traveller_historys, 'g_user':guide_user, 'guide_reviews': guide_reviews, 'traveller_reviews': traveller_reviews, 'ongoing_guide_tours': ongoing_guide_tours, 'ongoing_traveller_tours': ongoing_traveller_tours, } if (len(bio)>=5): bio_second = bio[5] context.update({ 'bio_second': bio_second, 'guide_reviews': guide_reviews, 'guide_historys': guide_historys, 'traveller_historys': traveller_historys, 'g_user':guide_user1, 'traveller_reviews': traveller_reviews, }) if(traveller_user.is_guide): context.update({'g_user':guide_user1,}) if (request.method == "POST" ): root_user = get_object_or_404(User, email=user) traveller_user = get_object_or_404(Traveller, email=user) if 'Update Profile' in request.POST: traveller_user.first_name = request.POST['first_name'].title() traveller_user.last_name = request.POST['last_name'].title() traveller_user.address = request.POST['address'].title() traveller_user.slogan = request.POST['slogan'] traveller_user.bio = request.POST['bio'] traveller_user.languages = request.POST['languages'] traveller_user.gender = request.POST['gender'] if request.FILES: traveller_user.photo_main = request.FILES['photo_main'] traveller_user.save() root_user.first_name = request.POST['first_name'].title() root_user.last_name = request.POST['last_name'].title() print(traveller_user.photo_main) root_user.save() return redirect ('dashboard') #for guide creation form if 'Guide-Form' in request.POST: GuideView(request) #calls guide's view in guide app if 'Guide-Update-Form' in request.POST: GuideUpdateView(request) if 'trip_reject' in request.POST: nid = request.POST['nid'] t_noti = get_object_or_404(Trip_Notification, pk=nid) t_noti.has_rejected = True t_noti.save() if 'pub_off' in request.POST: print(request.POST) guide_user1.is_active = False guide_user1.save() if 'pub_on' in request.POST: print(request.POST) guide_user1.is_active = True guide_user1.save() #for notification # if 'request_guide' in request.POST: # notifi 'tamt':tamt, # return redirect('dashboard') sender_user = request.user if 'accepted' in request.POST: receiver_email = request.POST['receiver_email'] receiver_user = get_object_or_404(User,email=receiver_email) sender_user = request.user sender_name = sender_user.first_name+" " +sender_user.last_name reg_date = datetime.datetime.utcnow().replace(tzinfo=utc) noti_id = request.POST['noti_id'] noti = get_object_or_404(Notification, pk=noti_id) noti.completed = True noti.save() notification = Notification(receiver_email=receiver_user, sender_email=sender_user, sender_name = sender_name,is_accepted = True, reg_date= reg_date) notification.save() chat = Chat( sender = sender_user, receiver = receiver_user, message_text = f'Hi, I\'m {sender_user.first_name} {sender_user.last_name}.\ Thank you for choosing me to be your guide. I\'d be happy to discuss the details with you' ) chat.save() messages.info(request, f'you can chat with {receiver_user.email} now') if 'ignored' in request.POST: noti_id = request.POST['noti_id'] receiver_email = request.POST['receiver_email'] receiver_user = get_object_or_404(User,email=receiver_email) sender_user = request.user sender_name = sender_user.first_name+" " +sender_user.last_name reg_date = datetime.datetime.utcnow().replace(tzinfo=utc) noti_id = request.POST['noti_id'] noti = get_object_or_404(Notification, pk=noti_id) noti.completed = True noti.save() notification = Notification(receiver_email=receiver_user, sender_email=sender_user, sender_name = sender_name,is_ignored = True, reg_date= reg_date) notification.save() if 'trip_complete_by_guide' in request.POST: history_id = request.POST['history_id'] history = get_object_or_404(History,pk=history_id) history.confirmed_by_guide=True if history.confirmed_by_traveller: history.tour_complete=True history.end_date = datetime.datetime.utcnow().replace(tzinfo=utc) history.save() return redirect ('dashboard') if 'trip_complete_by_traveller' in request.POST: history_id = request.POST['history_id'] history = get_object_or_404(History,pk=history_id) history.confirmed_by_traveller=True if history.confirmed_by_guide: history.tour_complete=True history.end_date = datetime.datetime.utcnow().replace(tzinfo=utc) history.save() return redirect ('dashboard') return render(request, 'dashboard/dashboard.html',context)