def add_friend(request):
	if not request.user.is_authenticated():
		return redirect(gethome())
	if request.method != 'POST':
		return redirect(gethome())
	else:			
		print "HELLO I AM AT AN AJAX CALL AT FRIENDS.VIEW.add_friend-----------------------------------------------------"
		print request.POST
		if "user2" in request.POST:
			user2_id = request.POST["user2"] 
			Profile2_object = Profile.objects.filter(id=user2_id)
			user2 = Profile2_object[0].user
			user1 = request.user #user who clicked add friend ==> userFrom

			message = Profile2_object[0].first_name + " " + Profile2_object[0].last_name + " wants to be friends with you"
			if checkFriendExisted(user1,user2) == True:
				return redirect(gethome())
			#-------------BETA-------------------------------------#
			user2_uuid = Profile2_object[0].id
			user1_uuid = Profile.objects.filter(user=user1)[0].id
			#-------------BETA-------------------------------------#
			friend_object = Friends(user1=user1,user2=user2,status = "P",user1_uuid=user1_uuid,user2_uuid=user2_uuid)
			friend_object.save()
			if(checkNotificationExisted(user1,user2,"F") == False):
				notification_object = Notification( user1=user1,
													user2=user2,
													message=message,
													read=False,
													notification_type="FR",
													target_id=friend_object.friends_id,
													user1_uuid=user1_uuid,
													user2_uuid=user2_uuid)
				notification_object.save()
			print "-------------DONE-----------------"
		return redirect(gethome())
def add_friend(request):
	if request.method == "POST" and request.is_ajax():
		context = {}
		user1 = request.user
		user1_profile = Profile.objects.get(user=user1)		
		user1_uuid = user1_profile.id
		user2_uuid = request.POST['user2_uuid']
		user2_profile = Profile.objects.get(id=user2_uuid)
		user2 = user2_profile.user
		friend_object = Friends(user1=user1,user2=user2,status = "P",user1_uuid=user1_uuid,user2_uuid=user2_uuid)
		message = user1_profile.first_name + " " + user1_profile.last_name + "shows interest with you"
		friend_object.save()
		notification_object = Notification(
											user1=user1,
											user2=user2,
											message=message,
											read=False,
											notification_type="I",
											target_id=friend_object.roomate_id,
											user1_uuid=user1_uuid,
											user2_uuid=user2_uuid,
										  )
		notification_object.save()							
		return render(request,"error.html",{})
	return render(request,"error.html",{})
Beispiel #3
0
    def test_notification_send(self):
        notifications = Notification.objects.all()
        self.assertEqual(1, len(notifications))
        self.assertEqual(self.student.userprofile, notifications[0].sender)
        self.assertEqual(self.teacher.userprofile, notifications[0].recipient)
        self.assertEqual(self.course_instance, notifications[0].course_instance)
        self.assertEqual("testSubject", notifications[0].subject)
        self.assertEqual("testNotification", notifications[0].notification)
        self.assertFalse(notifications[0].seen)

        Notification.send(self.teacher.userprofile, self.student.userprofile, self.course_instance, "subject", "notification")
        notifications = Notification.objects.all()
        self.assertEqual(2, len(notifications))
        self.assertEqual(self.teacher.userprofile, notifications[0].sender)
        self.assertEqual(self.student.userprofile, notifications[0].recipient)
        self.assertEqual(self.course_instance, notifications[0].course_instance)
        self.assertEqual("subject", notifications[0].subject)
        self.assertEqual("notification", notifications[0].notification)
        self.assertFalse(notifications[0].seen)
        self.assertEqual(self.student.userprofile, notifications[1].sender)
        self.assertEqual(self.teacher.userprofile, notifications[1].recipient)
        self.assertEqual(self.course_instance, notifications[1].course_instance)
        self.assertEqual("testSubject", notifications[1].subject)
        self.assertEqual("testNotification", notifications[1].notification)
        self.assertFalse(notifications[1].seen)
Beispiel #4
0
def add_tweet(request):
    html = 'add_tweet.html'
    notifcation_count = Notification.objects.filter(user=request.user).count()
    if request.method == "POST":
        form = AddTweetForm(request.POST)
        if form.is_valid():
            new_tweet = form.save(commit=False)
            new_tweet.profile = request.user
            new_tweet.save()

            # check to see if there is any mentions and add notification if there is
            reg = re.compile(r'(.*)(@\S*)')
            m = reg.match(new_tweet.content)
            if m:
                if Profile.objects.filter(handle=m[2][1:]):
                    new_notification = Notification(
                        user=Profile.objects.get(handle=m[2][1:]),
                        tweet=new_tweet)
                    new_notification.save()

        return HttpResponseRedirect(reverse('homepage'))
    form = AddTweetForm()
    return render(request, html, {
        'form': form,
        'notifcation_count': notifcation_count
    })
def generateDangerNotification(request):
	user = request.user
	bankingP = BankingPerson.objects.get(user=user)
	if bankingP.receiveDanger:
		n = Notification(title="Danger danger, we're gonna die", text="LAY, indeed, thought I, and such a lay! the seven hundred and seventy-seventh! Well, old Bildad, you are determined that I, for one, shall not LAY up many LAYS here below, where moth and rust do corrupt. It was an exceedingly LONG LAY that, indeed; and though from the magnitude of the figure it might at first deceive a landsman, yet the slightest consideration will show that though seven hundred and seventy-seven is a pretty large number, yet, when you come to make a TEENTH of it, you will then see, I say, that the seven hundred and seventy-seventh part of a farthing is a good deal less than seven hundred and seventy-seven gold doubloons; and so I thought at the time.", level = 3, to=user)
		n.save()
	return HttpResponseRedirect("/")
Beispiel #6
0
    def form_valid(self, form):
        assistant_feedback = form.cleaned_data["assistant_feedback"]
        feedback = form.cleaned_data["feedback"]

        note = ""
        if self.submission.assistant_feedback != assistant_feedback:
            note = assistant_feedback
        elif self.submission.feedback != feedback:
            note = feedback

        self.submission.set_points(form.cleaned_data["points"],
            self.exercise.max_points, no_penalties=True)
        self.submission.grader = self.profile
        self.submission.assistant_feedback = assistant_feedback
        self.submission.feedback = feedback
        self.submission.set_ready()
        self.submission.save()

        sub = _('Feedback to {name}').format(name=self.exercise)
        msg = _('<p>You have new personal feedback to exercise '
                '<a href="{url}">{name}</a>.</p>{message}').format(
            url=self.submission.get_absolute_url(),
            name=self.exercise,
            message=note,
        )
        for student in self.submission.submitters.all():
            Notification.send(self.profile, student, self.instance, sub, msg)

        messages.success(self.request, _("The review was saved successfully "
            "and the submitters were notified."))
        return super().form_valid(form)
Beispiel #7
0
def reply_topic(request, pk, topic_pk):
    topic = get_object_or_404(Topic, board__pk=pk, pk=topic_pk)
    if request.method == 'POST':
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            post = form.save(commit=False)
            post.topic = topic
            post.created_by = request.user
            post.save()

            topic.last_updated = timezone.now()
            topic.save()

            topic_url = reverse('topic_posts', kwargs={
                                'pk': pk, 'topic_pk': topic_pk})

            if post.created_by.username != topic.starter.username:
                topic_notif = post.created_by.username + ' replied to ' + topic.subject
                notif = Notification(
                    user=topic.starter, message=topic_notif, level=2, link=topic_url, fa_type='fa-edit')
                notif.save()

            messages.add_message(request, messages.SUCCESS,
                                 'Reply to the topic successfull.')

            return redirect('topic_posts', pk=pk, topic_pk=topic_pk)
    else:
        form = PostForm()
    return render(request, 'reply_topic.html', {'topic': topic, 'form': form})
def show_interest(request):
	if request.method == "POST" and request.is_ajax():
		print "AJAX------------------------------------SHOW INTEREST"
		context = {}
		#----GET VARIABLES---#
		user1 = request.user
		user1_profile = Profile.objects.get(user=user1)		
		user1_uuid = user1_profile.id
		user2_uuid = request.POST['user2_uuid']
		user2_profile = Profile.objects.get(id=user2_uuid)
		user2 = user2_profile.user
		#----INTERESTS ARE DIRECTED GRAPHS----#
		friends_object = Friends(user1=user1,user2=user2,status = "I",user1_uuid=user1_uuid,user2_uuid=user2_uuid)
		friends_object.save()
		message = user1_profile.first_name + " " + user1_profile.last_name + " shown interest on you"
		notification_object = Notification(
											user1=user1,
											user2=user2,
											message=message,
											read=False,
											notification_type="SI",
											target_id=friends_object.friends_id,
											user1_uuid=user1_uuid,
											user2_uuid=user2_uuid
											)
		notification_object.save()					
		print user2_uuid;
		notification_delete = request.POST['notification_delete']
		if notification_delete == "ok":
			notification_id = request.POST['notification_id']
			notification_object_delete = Notification.objects.get(notification_id=notification_id)
			notification_object_delete.delete()	

		return render(request,'error.html',context)
	return render(request,'error.html',{})
def generateWarningNotification(request):
	user = request.user
	bankingP = BankingPerson.objects.get(user=user)
	if bankingP.receiveWarning:
		n = Notification(title="BE WARNED, mortal", text="But one thing, nevertheless, that made me a little distrustful about receiving a generous share of the profits was this: Ashore, I had heard something of both Captain Peleg and his unaccountable old crony Bildad; how that they being the principal proprietors of the Pequod, therefore the other and more inconsiderable and scattered owners, left nearly the whole management of the ship's affairs to these two. And I did not know but what the stingy old Bildad might have a mighty deal to say about shipping hands, especially as I now found him on board the Pequod, quite at home there in the cabin, and reading his Bible as if at his own fireside. Now while Peleg was vainly trying to mend a pen with his jack-knife, old Bildad, to my no small surprise, considering that he was such an interested party in these proceedings; Bildad never heeded us, but went on mumbling to himself out of his book, 'LAY not up for yourselves treasures upon earth, where moth.", level = 2, to=user)
		n.save()
	return HttpResponseRedirect("/")
Beispiel #10
0
 def save(self, *args, **kwargs):
     markdown = Markdown()
     self.content_html = markdown.render(self.content)
     super().save(*args, **kwargs)
     from notification.models import Notification
     Notification.create_notifications_from_reply(
         reply=self, mentions=markdown.get_mentions())
Beispiel #11
0
def event_register(request, slug):
    if not request.user.is_authenticated:
        return redirect('{}?next={}'.format(settings.LOGIN_URL, request.path))

    attendee_name = request.user.first_name
    attendee_surname = request.user.last_name
    attendee_email = request.user.email

    form = EventRegisterForm(request.POST or None,
                             request.FILES or None,
                             initial={
                                 'first_name': attendee_name,
                                 'last_name': attendee_surname,
                                 'email': attendee_email,
                             })
    if form.is_valid():
        # name = form.cleaned_data.get('first_name')
        # surname = form.cleaned_data.get('last_name')
        # email = form.cleaned_data.get('email')
        event = get_object_or_404(Event, slug=slug)
        request.user.registered_events.add(event)
        Notification.send(actor=event,
                          receiver=event.organizer,
                          message='Your event has a new attendee.')
        messages.success(request, "You have successfuly registered the event.")
        return HttpResponseRedirect(event.get_absolute_url())
    return render(request, "crispy/form.html", {
        "form": form,
        "title": "Register Event"
    })
Beispiel #12
0
 def envoyer_commentaire_notification(self, comment_pk, username):
     eleve = UserProfile.objects.get(user__username=username)
     message = eleve.first_name + " " + eleve.last_name + " a commente un message de " + self.association.nom
     commentaire = Comment.objects.get(pk=comment_pk)
     notification = Notification(content_object=commentaire, description=message)
     notification.save()
     notification.envoyer_multiple(self.association.suivi_par.all())
def add_roomate(request):
	print "AJAX---------------------------------------ROOMATE REQUEST"

	if request.method == "POST" and request.is_ajax():
		print "AJAX----ADD_ROOMATE"
		context = {}
		user1 = request.user
		user1_profile = Profile.objects.get(user=user1)		
		user1_uuid = user1_profile.id
		user2_uuid = request.POST['user2_uuid']
		user2_profile = Profile.objects.get(id=user2_uuid)
		user2 = user2_profile.user
		roomate_object = Roomate(user1=user1,user2=user2,status = "P",user1_uuid=user1_uuid,user2_uuid=user2_uuid)
		roomate_object.save()
		message = user1_profile.first_name + " " + user1_profile.last_name + " wants to be roomates with you"
		notification_object = Notification(
											user1=user1,
											user2=user2,
											message=message,
											read=False,
											notification_type="RR",
											target_id=roomate_object.roomate_id,
											user1_uuid=user1_uuid,
											user2_uuid=user2_uuid
											)
		notification_object.save()					
		print user2_uuid;
		return render(request,'error.html',context)
	return render(request,'error.html',{})
Beispiel #14
0
    def test_notification_updated_on_request_aborted(self):
        project = self.create(Project, role=self.admin_role)
        normal_user = self.create(User)

        join_request = ProjectJoinRequest.objects.create(
            project=project,
            requested_by=normal_user,
            role=self.normal_role,
            data={'reason': 'bla'})

        # Get notification for self.user
        notifications = Notification.get_for(self.user)
        assert notifications.count() == 1
        assert notifications[0].notification_type ==\
            Notification.Type.PROJECT_JOIN_REQUEST
        assert notifications[0].data['status'] == 'pending'

        # Now abort join request by deleting it
        join_request.delete()

        # Get notifications again
        notifications = Notification.get_for(self.user)
        assert notifications.count() == 2
        new_notif = notifications.order_by('-timestamp')[0]
        assert new_notif.data['status'] == 'aborted'
        assert new_notif.notification_type ==\
            Notification.Type.PROJECT_JOIN_REQUEST_ABORT

        # Get notifications for requesting user
        # there should be none
        notifications = Notification.get_for(normal_user)
        assert notifications.count() == 0
Beispiel #15
0
def register_pill_by_name(request):
    '''This method is for the autosuggestion used in manual lookup. This method is for registering pills using the name, not the id'''
    if request.method == 'POST':
        if request.user.is_authenticated:
            try:
                req_data = json.loads(request.body.decode())
            except (KeyError, ValueError):
                return HttpResponseBadRequest()
            pill_name = req_data['pill_name']
            pill_company = req_data['pill_company']
            new_pill = Pill.objects.get(product_name=pill_name,
                                        company_name=pill_company,
                                        custom=False)
            existing_pill_names = request.user.pills.all().values_list(
                'product_name', flat=True)
            if pill_name in existing_pill_names:
                return HttpResponse(status=status.HTTP_400_BAD_REQUEST)
            request.user.pills.add(new_pill)
            Notification.create(request.user, new_pill)
            new_pill_dict = get_pill_dict(new_pill)
            return JsonResponse(new_pill_dict, status=status.HTTP_201_CREATED)
        else:
            return HttpResponse(status=401)
    else:
        return HttpResponseNotAllowed(['POST'])
Beispiel #16
0
    def change_status(self, value):
        not_send_notification_statuses = (
            "wait",
            "payment_check",
            "inspector_check",
        )

        if self.status is not value:
            self.status = value
            self.save()

            if self.status not in not_send_notification_statuses:
                notification = Notification(owner=self.owner,
                                            boat=self,
                                            status=self.status)
                notification.save()

                sms_message = get_message_text_by_status(
                    status=self.status,
                    boat_name=self.name,
                    extra_data=notification.extra_data)

                if sms_message:
                    send_sms(self.owner.phone_number, sms_message)

                if notification.status == "payment_rejected":
                    notification.boat.change_status("payment")
Beispiel #17
0
    def test_notification_created_on_project_join_request(self):
        project = self.create(Project, role=self.admin_role)
        # Create users
        normal_user = self.create(User)
        admin_user = self.create(User)

        # Add admin user to project
        project.add_member(admin_user, role=self.admin_role)
        ProjectJoinRequest.objects.create(project=project,
                                          requested_by=normal_user,
                                          role=self.normal_role,
                                          data={'reason': 'bla'})
        # Get notifications for admin_users
        for user in [self.user, admin_user]:
            notifications = Notification.get_for(user)
            assert notifications.count() == 1,\
                "A notification should have been created for admin"

            notification = notifications[0]
            assert notification.status == Notification.Status.UNSEEN
            assert notification.notification_type ==\
                Notification.Type.PROJECT_JOIN_REQUEST
            assert notification.receiver == user
            assert notification.data['status'] == 'pending'
            assert notification.data['data']['reason'] is not None

        # Get notifications for requesting user
        # there should be none
        notifications = Notification.get_for(normal_user)
        assert notifications.count() == 0
Beispiel #18
0
    def post(self, request, pill_id):
        """ add new pill item for user <int:pk> """
        if request.user.is_authenticated:
            # check if pill_id already exists in user's pills
            existing_pills = request.user.pills.all().values_list('id',
                                                                  flat=True)
            if pill_id in existing_pills:
                return HttpResponse(status=status.HTTP_400_BAD_REQUEST)

            # get pill object from Pill model by id
            new_pill = Pill.objects.get(pk=pill_id)
            # add retrieved pill object to current user's pills field
            request.user.pills.add(new_pill)
            # add notification for the new pill
            Notification.create(request.user, new_pill)

            image_query = Image.objects.filter(user=request.user,
                                               pill=new_pill)
            if image_query.exists():
                image_instance = image_query[0]
                new_pill_dict = get_pill_dict(new_pill, image_instance)
            else:
                new_pill_dict = get_pill_dict(new_pill)

            # new_pill_dict = get_pill_dict(new_pill)
            return JsonResponse(new_pill_dict, status=status.HTTP_201_CREATED)
        else:
            return HttpResponse(status=status.HTTP_401_UNAUTHORIZED)
def team_invite(request):
    # Get POST data
    payload = request.POST.get('value')
    # Try to decode the scrambled team pk
    try:
        data = decode_data(payload)
    except Exception:
        print("bad hash")
        return JsonResponse({'status': 'ko'})

    user_id = int(data[0])
    team_id = int(data[1])

    # Try to get the team
    try:
        team = get_object_or_404(Team, pk=team_id)
    except Http404:
        print("team not found", team_id)
        return JsonResponse({'status': 'ko'})

    # Double check that the request does not already exist
    if Notification.objects.filter(
            user_from=request.user,
            user_to_id=user_id,
            foreignPK=team_id,
            context=Notification.contexts.team.name,
            action=Notification.actions.team_invite.name,
            url=payload,
            read=False,
    ).exists():
        print("did exist")
        return JsonResponse({'status': 'ko'})
    # Double check that the request does not already exist
    elif Notification.objects.filter(
            user_from_id=user_id,
            foreignPK=team_id,
            context=Notification.contexts.team.name,
            action=Notification.actions.team_req_join,
            url=payload,
            read=False,
    ).exists():
        print("did exist")
        return JsonResponse({'status': 'ko'})

    # Generate payload
    payload = encode_data([request.user.pk, team_id])

    # Generate a request notification
    notif_req = Notification(
        user_from=request.user,
        user_to_id=user_id,
        foreignPK=team_id,
        context=Notification.contexts.team.name,
        action=Notification.actions.team_invite.name,
        url=payload,
    )
    notif_req.save()

    # Return a successful response
    return JsonResponse({'status': 'ok'})
def generateInfoNotification(request):
	user = request.user
	bankingP = BankingPerson.objects.get(user=user)
	if bankingP.receiveInfo:
		n = Notification(title="Information triggered", text="I thought him the queerest old Quaker I ever saw, especially as Peleg,his friend and old shipmate, seemed such a blusterer. But I said nothing, only looking round me sharply. Peleg now threw open a chest, and drawing forth the ship's articles, placed pen and ink before him, and seated himself at a little table. I began to think it was high time to settle with myself at what terms I would be willing to engage for the voyage. I was already aware that in the whaling business they paid no wages; but all hands, including the captain, received certain shares of the profits called lays, and that these lays were proportioned to the degree of importance pertaining to the respective duties of the ship's company. I was also aware that being a green hand at whaling, my own lay would not be very large; but considering that I was used to the sea, could steer a ship, splice a rope, and all that, I made no doubt that from all I had heard I should be offered at least the 275th lay--that is, the 275th part of the clear net proceeds of the voyage, whatever that might eventually amount to. And though the 275th lay was what they call a rather LONG LAY, yet it was better than nothing; and if we had a lucky voyage, might pretty nearly pay for the clothing I would wear out on it, not to speak of my three years' beef and board, for which I would not have to pay one stiver.", level = 0, to=user)
		n.save()
	return HttpResponseRedirect("/")
 def handle(self, *args, **kwargs):
     now = timezone.now()
     meal_list = Meal.objects.filter(
         scheduled_for__lt=now,
         review__isnull=True,
         status='a',
     )
     for meal in meal_list:
         print "Creating a KitchenReview object and sending email " \
             "for meal with ID: %d" % meal.id
         token = get_random_string()
         kitchen_review = KitchenReview.objects.create(
             token=token,
             guest=meal.guest,
             kitchen=meal.kitchen,
         )
         meal.review = kitchen_review
         meal.save()
         Notification.notify(
             'invite_guest_review', {
                 'to_address': meal.guest.email,
                 'meal': meal,
                 'kitchen_review': kitchen_review,
             }
         )
def LikeView(request):

    post = get_object_or_404(Post, id=request.POST.get('id'))
    liked = False
    if post.likes.filter(id=request.user.id).exists():
        post.likes.remove(request.user)
        liked = False
        notify = Notification.objects.filter(post=post,
                                             sender=request.user,
                                             notification_type=1)
        notify.delete()
    else:
        post.likes.add(request.user)
        liked = True
        notify = Notification(post=post,
                              sender=request.user,
                              user=post.author,
                              notification_type=1)
        notify.save()

    context = {
        'post': post,
        'total_likes': post.total_likes(),
        'liked': liked,
    }

    if request.is_ajax():
        html = render_to_string('blog/like_section.html',
                                context,
                                request=request)
        return JsonResponse({'form': html})
Beispiel #23
0
    def form_valid(self, form):
        assistant_feedback = form.cleaned_data["assistant_feedback"]
        feedback = form.cleaned_data["feedback"]

        note = ""
        if self.submission.assistant_feedback != assistant_feedback:
            note = assistant_feedback
        elif self.submission.feedback != feedback:
            note = feedback

        self.submission.set_points(form.cleaned_data["points"],
                                   self.exercise.max_points,
                                   no_penalties=True)
        self.submission.grader = self.profile
        self.submission.assistant_feedback = assistant_feedback
        self.submission.feedback = feedback
        self.submission.set_ready()
        self.submission.save()

        #sub = _('Feedback to {name}').format(name=self.exercise)
        #msg = _('<p>You have new personal feedback to exercise '
        #        '<a href="{url}">{name}</a>.</p>{message}').format(
        #    url=self.submission.get_absolute_url(),
        #    name=self.exercise,
        #    message=note,
        #)
        Notification.send(self.profile, self.submission)

        messages.success(
            self.request,
            _("The review was saved successfully "
              "and the submitters were notified."))
        return super().form_valid(form)
Beispiel #24
0
 def post(self, request, *args, **kwargs):
     check_if_user(request)
     id = request.user.id
     user = TemplateUser.objects.get(id=id)
     following = request.data['following']
     query = Follow.objects.filter(following=following, follower=user)
     if query:
         raise ValidationError(
             {"detail": 'You have already follow this person'})
     user_following = TemplateUser.objects.filter(id=following).first()
     if not user_following:
         raise ValidationError({"detail": 'User does not exist'})
     if user_following.is_public:
         data = {
             "follower": user,
             "following": following,
             "is_active": True
         }
     else:
         data = {
             "follower": user,
             "following": following,
             "is_active": False
         }
     serializer = FollowCreateSerializer(data=data)
     serializer.is_valid(raise_exception=True)
     serializer.save()
     if not user_following.is_public:
         new_notif = Notification(owner=user_following,
                                  text=request.user.username +
                                  " wants to follow you",
                                  date=datetime.now())
         new_notif.save()
     return Response(serializer.data, status=200)
def persistNotif(notification):

    serializedAudience = " "

    for a in notification["audience"]:
        serializedAudience += (a + " ")

    notif = Notification(audience=serializedAudience,
                         medium=notification["medium"],
                         notif_type=notification["type"],
                         params=json.dumps(notification["params"]),
                         seen="")

    notif.save()

    notification['created_date'] = {
        "day": notif.created_date.day,
        "month": notif.created_date.month,
        "year": notif.created_date.year,
        "hour": notif.created_date.hour,
        "minute": notif.created_date.minute,
        "second": notif.created_date.second
    }

    notification['notif_id'] = notif.id
    notification['seen'] = notif.seen

    return notif
Beispiel #26
0
def upload_photo(request):
	if request.method == 'POST':
		sim_file= request.FILES['sim_id']
		f=sim_file.read()
		sim_id=int(f)
		#test if Sim with number=sim_id  exists
		if Sim.objects.filter(number = sim_id).count()==1:
			#Creating Photo object
			uploaded_photo = Photo(phototype= 'Blank', image = request.FILES['file_upload'])
			#Creating Notification object and save to DBB
			mySim=Sim.objects.get(number = sim_id)
			myBox=Box.objects.get(sim = mySim)
			if Notification.objects.filter(title__contains = uploaded_photo.image).count() > 1:
				i=0
				for notification in Notification.objects.filter(title__contains = uploaded_photo.image):
					i+=1			
				titleu=str(uploaded_photo.image) + str(i)
				myNotification = Notification(title = titleu, box=myBox)
			else:
				myNotification = Notification(title = uploaded_photo.image, box=myBox)
			#Traitement d'image
			myNotification.save()
			#Polishing Photo object and save to DBB
			uploaded_photo.notification=myNotification
			uploaded_photo.save()
			#to remove str(sim_id)
			return HttpResponse("Image Uploaded, owner of sim_id = " + str(sim_id))
		else:
			return HttpResponse("ACCESS DENIED: Box Not Identified")
	else:
		return HttpResponse("GET Denied")
Beispiel #27
0
    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()
Beispiel #28
0
def _post_async_submission(request, exercise, submission, errors=None):
    """
    Creates or grades a submission.

    Required parameters in the request are points, max_points and feedback. If
    errors occur or submissions are no longer accepted, a dictionary with
    "success" is False and "errors" list will be returned.
    """
    if not errors:
        errors = []

    # The feedback field may contain null characters, which would invalidate
    # the form before its clean method is executed. So replace them beforehand.
    post_data = request.POST.copy()
    feedback = post_data.get('feedback')
    if feedback:
        post_data['feedback'] = feedback.replace('\x00', '\\x00')

    # Use form to parse and validate the request.
    form = SubmissionCallbackForm(post_data)
    errors.extend(extract_form_errors(form))
    if not form.is_valid():
        submission.feedback = _(
            "ERROR_ALERT_EXERCISE_ASSESSMENT_SERVICE_MALFUNCTIONING")
        submission.set_error()
        submission.save()
        if exercise.course_instance.visible_to_students:
            msg = "Exercise service returned with invalid grade request: {}"\
                .format("\n".join(errors))
            logger.error(msg, extra={"request": request})
            email_course_error(request, exercise, msg, False)
        return {"success": False, "errors": errors}

    # Grade the submission.
    try:
        submission.set_points(form.cleaned_data["points"],
                              form.cleaned_data["max_points"])
        submission.feedback = form.cleaned_data["feedback"]
        submission.grading_data = post_data

        if form.cleaned_data["error"]:
            submission.set_error()
        else:
            submission.set_ready()
        submission.save()

        if form.cleaned_data["notify"]:
            Notification.send(None, submission)
        else:
            Notification.remove(submission)

        return {"success": True, "errors": []}

    # Produce error if something goes wrong during saving the points.
    except Exception as e:
        logger.exception("Unexpected error while saving grade"
                         " for {} and submission id {:d}".format(
                             str(exercise), submission.id))
        return {"success": False, "errors": [repr(e)]}
Beispiel #29
0
    def user_comment_post(sender, instance, *args, **kwargs):
        comment = instance
        post = comment.post
        text_preview = comment.body[:90]
        sender = comment.user

        notify = Notification(post=post, sender=sender, user=post.user, text_preview=text_preview, notification_type=2)
        notify.save()
def generateSuccessNotification(request):
	user = request.user
	bankingP = BankingPerson.objects.get(user=user)
	print bankingP.receiveSuccess
	if bankingP.receiveSuccess:
		n = Notification(title="Success may be on your way", text="hello world body", level = 1, to=user)
		n.save()
	return HttpResponseRedirect("/")
Beispiel #31
0
 def add(request, post_id):
     if request.method == 'POST':
         post = Post.objects.get(id=post_id)
         account = Account.get_by_user(request.user)
         post.add_link(account)
         Notification.add(post.publisher, account, NotificationType.ADD, post)
     redirect_path = request.GET['next']
     return redirect(redirect_path)
Beispiel #32
0
 def envoyer_notification(self):
     try: 
         bde = Association.objects.get(pseudo='bde') #On envoie seulement à ceux qui suivent le BDE
         notification = Notification(content_object=self, message='Un nouveau petit cours est disponible')
         notification.save()
         notification.envoyer_multiple(bde.suivi_par.all())
     except Association.DoesNotExist:
         pass
Beispiel #33
0
    def user_like_question(sender, instance, *args, **kwargs):
        like = instance
        question = like.question
        sender = like.auth

        notify = Notification(question=question, sender=sender,
                              receiver=question.auth, notification_type=2)
        notify.save()
Beispiel #34
0
    def user_add_answer(sender, instance, *args, **kwargs):
        ans = instance
        answer = ans.answer
        question = ans.question
        sender = ans.auth

        notify = Notification(answer=ans, question=question, sender=sender, receiver=ans.question.auth, notification_type=3)
        notify.save()
Beispiel #35
0
    def user_like_answer(sender, instance, *args, **kwargs):
        like = instance
        ans = like.ans
        sender = like.auth

        notify = Notification(answer=ans, sender=sender,
                              receiver=ans.auth, notification_type=1)
        notify.save()
Beispiel #36
0
def commentNotifction(sender, instance, created=None, **kwargs):
    print(instance.id,  'instalce ')
    if created:
        order = instance
        marchent = instance.marchant.user
    
        notify = Notification(order=order, marchent=marchent)
        notify.save()
Beispiel #37
0
def custompill_post(request):
    """ add new pill item for user <int:pk> """
    if request.user.is_authenticated:
        # check if pill_id already exists in user's pills
        try:
            pill_data = json.loads(request.body.decode())
            print(pill_data)
            take_method = pill_data['take_method']
            product_name = pill_data['product_name']
            expiration_date = pill_data['expiration_date']
            functions = pill_data['functions']
            print('error1')
            store_method = pill_data['store_method']
            company_name = pill_data['company_name']
            standards = pill_data['standards']
            precautions = pill_data['precautions']
            take_method_preprocessed = pill_data['take_method_preprocessed']
            image_id = pill_data['image_id']
            print('error')
        except (KeyError, ValueError):
            return HttpResponseBadRequest()
        existing_pills = request.user.pills.all().values_list('product_name',
                                                              flat=True)
        if product_name in existing_pills:
            return HttpResponse(status=status.HTTP_400_BAD_REQUEST)

        print(pill_data)

        # get pill object from Pill model by id
        new_pill = CustomPill.objects.create(
            user=request.user,
            take_method=take_method,
            product_name=product_name,
            expiration_date=expiration_date,
            functions=functions,
            store_method=store_method,
            company_name=company_name,
            standards=standards,
            precautions=precautions,
            take_method_preprocessed=take_method_preprocessed,
            custom=True,
        )

        # Assign pill to image
        image_instance = Image.objects.get(id=image_id)
        image_instance.pill = new_pill
        image_instance.user = request.user
        image_instance.save()

        # add retrieved pill object to current user's pills field
        request.user.pills.add(new_pill)
        # add notification for the new pill
        Notification.create(request.user, new_pill)

        return JsonResponse(get_pill_dict(new_pill),
                            status=status.HTTP_201_CREATED)
    else:
        return HttpResponse(status=status.HTTP_401_UNAUTHORIZED)
Beispiel #38
0
 def like_notification(sender, instance, *args, **kwargs):
     like = instance
     post = like.post
     sender = like.user
     notify = Notification(post=post,
                           sender=sender,
                           receiver=post.user,
                           type='Like')
     notify.save()
Beispiel #39
0
 def envoyer_notification(self, eleve):
     if eleve.user.associations_suivies.filter(pseudo='mediamines'):
         try: #Des gens ont peut etre deja été identifiés sur cette photo, il faut retrouver la notification
             notification = Notification.objects.get(content_type = ContentType.objects.get_for_model(self), object_id = self.id)
             notification.envoyer(eleve.user)
         except Notification.DoesNotExist: #En fait non, cette notification n'existe pas. On la crée.
             notification = Notification(content_object=self, message='Vous avez été identifié sur une photo de MediaMines')
             notification.save()
             notification.envoyer(eleve.user)
def team_req_join(request):
    # Get POST data
    teamHash = request.POST.get('team')
    # Try to decode the scrambled team pk
    try:
        teamPK = decode_value(teamHash)
    except Exception:
        print("bad hash")
        return JsonResponse({'status': 'ko'})

    # Try to get the team
    try:
        team = get_object_or_404(Team, pk=teamPK)
    except Http404:
        print("team not found", teamPK)
        return JsonResponse({'status': 'ko'})

    # Double check that the request does not already exist
    if Notification.objects.filter(
            user_from=request.user,
            user_to=team.author,
            foreignPK=teamPK,
            context=Notification.contexts.team.name,
            action=Notification.actions.team_req_join.name,
            read=False,
    ).exists():
        print("Did exist")
        return JsonResponse({'status': 'ko'})
    # Double check that the request does not already exist
    elif Notification.objects.filter(
            user_to=request.user,
            foreignPK=teamPK,
            context=Notification.contexts.team.name,
            action=Notification.actions.team_invite.name,
            read=False,
    ).exists():
        print("Did exist")
        return JsonResponse({'status': 'ko'})

    # Generate datahash
    print("Generating hash")
    notif_url = encode_data([request.user.pk, teamPK])
    print(notif_url)

    # Generate a request notification
    notif_req = Notification(
        user_from=request.user,
        user_to=team.author,
        foreignPK=teamPK,
        context=Notification.contexts.team.name,
        action=Notification.actions.team_req_join.name,
        url=notif_url,
    )
    notif_req.save()

    # Return a successful response
    return JsonResponse({'status': 'ok'})
Beispiel #41
0
 def save(self, *args, **kwargs):
     markdown = Markdown()
     self.content_html = markdown.render(self.content)
     super().save(*args, **kwargs)
     from notification.models import Notification
     Notification.create_notifications_from_reply(
         reply=self,
         mentions=markdown.get_mentions()
     )
Beispiel #42
0
def find_mention_notifications(tweet):
    mentions = re.findall(r'@(\w*)', tweet.content)
    if mentions:
        for user in mentions:
            mentioned_user = TwitterUser.objects.filter(username=user).first()
            if mentioned_user:
                new_notification = Notification(intended_for=mentioned_user,
                                                tweet=tweet)
                new_notification.save()
Beispiel #43
0
 def envoyer_notification(self):
     try: 
         perm = Permission.objects.get(codename='add_sondage')  #On envoie seulement à ceux qui peuvent créer des sondages
         users = User.objects.filter(Q(is_superuser=True) | Q(groups__permissions=perm) | Q(user_permissions=perm) ).distinct()            
         notification = Notification(content_object=self, description='Un nouveau sondage a été proposé')
         notification.save()
         notification.envoyer_multiple(users)
     except Permission.DoesNotExist:
         pass
Beispiel #44
0
def _post_async_submission(request, exercise, submission, errors=None):
    """
    Creates or grades a submission.

    Required parameters in the request are points, max_points and feedback. If
    errors occur or submissions are no longer accepted, a dictionary with
    "success" is False and "errors" list will be returned.
    """
    if not errors:
        errors = []

    # Use form to parse and validate the request.
    form = SubmissionCallbackForm(request.POST)
    errors.extend(extract_form_errors(form))
    if not form.is_valid():
        submission.feedback = _(
            "<div class=\"alert alert-error\">\n"
            "<p>The exercise assessment service is malfunctioning. "
            "Staff has been notified.</p>\n"
            "<p>This submission is now marked as erroneous.</p>\n"
            "</div>")
        submission.set_error()
        submission.save()
        if exercise.course_instance.visible_to_students:
            msg = "Exercise service returned with invalid grade request: {}"\
                .format("\n".join(errors))
            logger.error(msg, extra={"request": request})
            email_course_error(request, exercise, msg, False)
        return {"success": False, "errors": errors}

    # Grade the submission.
    try:
        submission.set_points(form.cleaned_data["points"],
                              form.cleaned_data["max_points"])
        submission.feedback = form.cleaned_data["feedback"]
        submission.grading_data = request.POST

        if form.cleaned_data["error"]:
            submission.set_error()
        else:
            submission.set_ready()
        submission.save()

        if form.cleaned_data["notify"]:
            Notification.send(None, submission)
        else:
            Notification.remove(submission)

        return {"success": True, "errors": []}

    # Produce error if something goes wrong during saving the points.
    except Exception as e:
        logger.exception("Unexpected error while saving grade"
                         " for {} and submission id {:d}".format(
                             str(exercise), submission.id))
        return {"success": False, "errors": [repr(e)]}
Beispiel #45
0
 def follow(request, username):
     if request.method == 'POST':
         relationship = Relationship()
         relationship.owner = Account.get_by_user(request.user)
         relationship.follow = Account.get_by_username(username)
         if not relationship.owner.is_following(relationship.follow):
             relationship.save()
             Notification.add(relationship.follow, relationship.owner,
                              NotificationType.FOLLOW)
         return redirect('profile', username)
Beispiel #46
0
 def react(request, post_id):
     if request.method == 'POST':
         reaction = Reaction()
         reaction.post = Post.objects.get(id=post_id)
         reaction.owner = Account.get_by_user(request.user)
         reaction.save()
         Notification.add(reaction.post.owner, reaction.owner,
                          NotificationType.REACT, reaction.post)
     redirect_path = request.GET['next']
     return redirect(redirect_path)
Beispiel #47
0
 def list(request):
     owner = request.user.accounts.first()
     notifications = Notification.objects.filter(
         owner=owner).order_by('-created_at')
     Notification.check_as_viewed(owner)
     notify_count = 0
     return render(request, 'notification/list.html', {
         'notifications': notifications,
         'notify_count': notify_count
     })
Beispiel #48
0
 def notify(self):
     # Guest confirmation
     Notification.notify('book_guest', {
         'to_address': self.guest.email,
         'meal': self,
     })
     # Chef confirmation
     Notification.notify('book_chef', {
         'to_address': self.kitchen.chef.email,
         'meal': self,
     })
Beispiel #49
0
	def setUp(self):
		self.user = factory.create_user('*****@*****.**', '*****@*****.**', 'john123', 'John', 'Doe')
		self.location = factory.create_location('Thailand', 'Nakhonsawan')
		self.category = factory.create_category('Travel', 'travel')
		self.blog = factory.create_blog('Travel in Nakhonsawan', self.user, self.category, self.location)

		self.love_user = factory.create_user('*****@*****.**', '*****@*****.**', 'adam123', 'Adam', 'Johnson')
		self.love_notification = Notification(subject=self.love_user, action=1, blog=self.blog)
		self.love_notification.save()

		self.download_notification = Notification(subject=self.user, action=2, blog=self.blog)
		self.download_notification.save()
Beispiel #50
0
def send_notification(request):
    params = request.POST  
    client_id = params['client_id']
    group_id = params['group_id']
    title = params['title']
    message = params['message']
    target_url = params['target_url']
    notification = Notification(title=title, message=message, target_url=target_url,
     client_id=client_id, group_id=group_id)
    notification.save()
    args = (user_list, title, message, target_url, notification_id)
    add_to_task(args, notification, client_id, group_id)
Beispiel #51
0
    def post(self, request, goal_slug, suggestion_slug):  # noqa
        self._get_data(request, goal_slug, suggestion_slug)
        if not self.review:
            self._create_review()

        data = ReviewSerializer(self.review).data
        data.update(request.data)

        serializer = ReviewSerializer(instance=self.review, data=data)
        if serializer.is_valid():
            self.review = serializer.save(is_draft=False)
            update_rating_and_save(self.review.revision.suggestion)
            self.review.comments.filter(is_draft=False).delete()
            notification = Notification.create_for_review(self.review)
            if notification.owner != self.review.owner:
                notification.save()
            return Response(
                {'success': 1},
                status=status.HTTP_200_OK
            )
        else:
            return Response(
                {
                    'success': 0,
                    'errors': serializer.errors
                },
                status=status.HTTP_200_OK
            )
def change_friend_status(request):
	if not request.user.is_authenticated():
		return redirect(gethome())

	if request.method != 'POST':
		print "NOT POST-----------------"
		return redirect(gethome())
	else:
		print "CHANGE REQUEST ENTER AJAX CALL--------------------------"
		print request.POST
		notification_id = request.POST['this_id']
		notification_object = Notification.objects.filter(notification_id=notification_id)
		response_type = str(request.POST['type']) 
		if "delete_notification" == response_type:
			print "DELETe NOTIFICATION--------------------AJAX------------------"			
			notification_object.delete()
			return redirect(gethome())

		target_id = request.POST['target_id']
		friend_object = Friends.objects.filter(friends_id=target_id)				
		#-------------BETA-------------------------------------#			
		user1_uuid = request.POST['user1_uuid']
		user2_uuid = request.POST['user2_uuid']
		#-------------BETA-------------------------------------#	
		if "accept" == response_type:
			print "ACCEPT-------------------AJAX------------------"
			friend_object.update(status="F")			
			notification_object.delete()
			#-------------BETA-------------------------------------#			
			profile1 = Profile.objects.get(id=user1_uuid)
			profile2 = Profile.objects.get(id=user2_uuid)
			#-------------BETA-------------------------------------#
			message =  str(profile2.first_name) + " " +str(profile2.last_name) +" " +"HAVE BECOME FRIENDS WITH YOU"
			accept_notification = Notification( user1=profile2.user,
												user2=profile1.user,
												message=message,
												user1_uuid=user2_uuid,
												user2_uuid=user1_uuid,
												notification_type="FA")
			accept_notification.save()
		elif "ignore" == response_type:
			print "IGNORE-------------------AJAX------------------"
			friend_object.delete()						
			notification_object.delete()			
		elif "block" == response_type:
			print "BLOCK--------------------AJAX------------------"
	return redirect(gethome())
Beispiel #53
0
def user_post_save(sender, instance, created, **kwargs):
    if created and not kwargs.get('raw', False):
        notification = Notification()
        notification.user = instance
        notification.save()
        address = Address()
        address.save(user=instance)
        profile = UserProfile()
        profile.user = instance
        profile.address = address
        profile.save()

        today = datetime.date.today()
        subscription = Subscription.objects.create(owner=instance,
                                                   state=SUBSCRIPTION_STATE_TRIAL,
                                                   expiration_date=today + datetime.timedelta(settings.TRIAL_DURATION),
                                                   transaction_id='TRIAL-%i%i%i-%i' % (today.year, today.month, today.day, instance.id))
Beispiel #54
0
class TestHelperFunction(TestCase):
	def setUp(self):
		self.user = factory.create_user('*****@*****.**', '*****@*****.**', 'john123', 'John', 'Doe')
		self.location = factory.create_location('Thailand', 'Nakhonsawan')
		self.category = factory.create_category('Travel', 'travel')
		self.blog = factory.create_blog('Travel in Nakhonsawan', self.user, self.category, self.location)

		self.user_with_notification = factory.create_user('*****@*****.**', '*****@*****.**', 'adam123', 'Adam', 'Johnson')
		self.notification = Notification(subject=self.user_with_notification, action=1, blog=self.blog)
		self.notification.save()

	def tearDown(self):
		rm_user(self.user.id)
		rm_user(self.user_with_notification.id)
		self.notification.delete()

	def test_get_notifications(self):
		self.assertEqual(1, len(get_notifications(self.user)))
		self.assertEqual(0, len(get_notifications(self.user_with_notification)))
Beispiel #55
0
def upload_test(request):
	if request.method == 'POST':
		sim_id= request.POST['sim_id']
		#test if Sim with number=sim_id  exists
		if Sim.objects.filter(number = sim_id).count()==1:
			#Creating Photo object
			uploaded_photo = Photo(phototype= 'Blank', image = request.FILES['file_upload'])
			#Creating Notification object and save to DBB
			mySim=Sim.objects.get(number = sim_id)
			myBox=Box.objects.get(sim = mySim)
			if Notification.objects.filter(title__contains = uploaded_photo.image).count() > 1:
				i=0
				for notification in Notification.objects.filter(title__contains = uploaded_photo.image):
					i+=1			
				titleu=str(uploaded_photo.image) + str(i)
				myNotification = Notification(title = titleu, box=myBox)
			else:
				myNotification = Notification(title = uploaded_photo.image, box=myBox)
			#Traitement d'image
			myNotification.save()
			#Polishing Photo object and save to DBB
			uploaded_photo.notification=myNotification
			uploaded_photo.save()
			#C:\Users\Elomario\Desktop\PI\Phase2\CMAIL-django\
			#notificationu=Notification.objects.get(title='test recette')
			#photou=Photo.objects.get(notification=notificationu)
			print(str(uploaded_photo.image))
			ls_fd = subprocess.Popen('static\SimpleColorDetection_TEST.exe ' + str(uploaded_photo.image),stdout=subprocess.PIPE).communicate()[0]
			print('done')
			out = ls_fd
			#ENDOFIMAGEHANDLING
			if "letter" in str(out):
				uploaded_photo.phototype='enveloppe'
			elif "colis" in str(out):
				uploaded_photo.phototype='colis'
			elif "pub" in str(out):
				uploaded_photo.phototype='pub'
			uploaded_photo.save()
			return HttpResponse("DO A POST " +  str(out))
			
		else:
			return HttpResponse("ACCESS DENIED: Box Not Identified")
Beispiel #56
0
 def envoyer_message_notification(self):
     message = self.association.nom + " a publie un nouveau message"
     notification = Notification(content_object=self, message=message)
     notification.save()
     if self.destinataire is None:
         notification.envoyer_multiple(self.association.suivi_par.all())
     else:
         recipients = self.association.suivi_par.all().filter(
             Q(userprofile__in=self.destinataire.membres.all) | Q(userprofile__in=self.association.membres.all)
         )
         notification.envoyer_multiple(recipients)
Beispiel #57
0
 def post(self, request):
     message={}
     if request.user.is_authenticated():
         objectid=request.POST.get('objectid','')
         objecttype=request.POST.get('objecttype','')
         votetype=request.POST.get('votetype','')
         if objectid and objecttype and votetype:
             if objecttype=='question':
                 currentobject=Question.objects.get(pk=objectid);
             elif objecttype=='answer':
                 currentobject=Answer.objects.get(pk=objectid);
             if currentobject:
                 if votetype=="vote":
                     if request.user.profile in currentobject.votes.all():
                         message['status']='False'
                         message['message']="Bạn chỉ được thích một lần"
                     else:
                         currentobject.votes.add(request.user.profile)
                         currentobject.save()
                         currentobject.author.rank+=0.01
                         currentobject.author.save()
                         message['status']='OK'
                         message['message']=""
                         message['votes_count']=currentobject.votes_count
                 elif votetype=="downvote":
                     if request.user.profile in currentobject.downvotes.all():
                         message['status']='False'
                         message['message']="Bạn chỉ được không thích một lần"
                     else:
                         currentobject.downvotes.add(request.user.profile)                            
                         currentobject.save()
                         currentobject.author.rank-=0.05
                         currentobject.author.save()
                         message['status']='OK'
                         message['message']=""
                         message['votes_count']=currentobject.downvotes_count
                 #notification
                 if currentobject.author!=request.user.profile:
                     notification=Notification()
                     notification.action=votetype
                     notification.sender=request.user.profile
                     notification.recipient=currentobject.author
                     notification.content_object=currentobject
                     notification.save()
             else:
                 message['status']='False'
                 message['message']="{} không tồn tại".format(objecttype)
         else:
             message['status']='False'
             message['message']='Thông tin không chính xác'
     else:
         message['status']='False'
         message['message']='Bạn cần đăng nhập'
     return HttpResponse(json.dumps(message), content_type = "application/json")
Beispiel #58
0
def send_notification(request):
    params = request.POST  
    client_id = params['client_id']
    group_id = params['group_id']
    title = params['title']
    message = params['message']
    target_url = params['target_url']
    notification_date = params['date']
    notification_time = params['time']
    notification = Notification(title=title, message=message, target_url=target_url, client_id=client_id, group_id=group_id)
    notification.save()
    notification_id = notification.id
    user_list = get_notification_user_list(client_id, group_id)
    record_list = [NotificationResponse(user_id=user['id'], notification_id=notification_id) for user in user_list]
    NotificationResponse.objects.bulk_create(record_list)
    if notification_date!='' and notification_time!='':
        notification_eta =  notification_date+' '+notification_time
        datetime_object = parser.parse(notification_eta)
        datetime_object = datetime_object.replace(tzinfo=None) + datetime_object.utcoffset()
    else:
        datetime_object = datetime.now()    
    push_notification.apply_async(args=(user_list, title, message, target_url, notification_id), eta=datetime_object)
    return JsonResponse({'success': True})
Beispiel #59
0
def queue_notification(sender_id, recipient_id, model_name, obj_id):
    """
    Adds a notification for an agree, thanks, bookmark, or follow.
    Increments the notification count in the cache.
        sender_id: agree.giver_id, thank.giver_id, bookmark.user_id,
            or backward.source_id
        recipient_id: agree.review.user_id, thank.review.user_id,
            0, or backward.destination_id
        model_name: string of class name
        obj_id: object.pk
    """
    model = get_model(MODEL_APP_NAME[model_name], model_name)
    try:
        pg_notification = Notification(
            sender=User.objects.get(pk=sender_id),
            recipient=User.objects.get(pk=recipient_id),
            notification_type=model_name
        )
        if model_name == "agree" or model_name == "thank":
            obj = model.objects.get(pk=obj_id)
            pg_notification.item = obj.review.item
            if model_name == "thank":
                pg_notification.note = obj.note
        pg_notification.save()

        if not cacheAPI._get_new_notifications_count(recipient_id):
            cacheAPI._reset_new_notifications_count(recipient_id)
        cacheAPI._increment_new_notifications_count(recipient_id)
        cacheAPI._cache_notification_for_user(pg_notification)
        announce_client.emit(
            recipient_id,
            'notification',
            data={ 'new': 1 } # Currently un-used
        )

    except ObjectDoesNotExist:
        pass
Beispiel #60
0
 def envoyer_commentaire_notification(self, comment_pk, username):
     eleve = UserProfile.objects.get(user__username=username)
     message = eleve.first_name + " " + eleve.last_name + " a commente un message de " + self.association.nom
     commentaire = Comment.objects.get(pk=comment_pk)
     notification = Notification(content_object=commentaire, message=message)
     notification.save()
     if self.destinataire is None:
         notification.envoyer_multiple(self.association.suivi_par.all())
     else:
         recipients = self.association.suivi_par.all().filter(
             Q(userprofile__in=self.destinataire.membres.all) | Q(userprofile__in=self.association.membres.all)
         )
         notification.envoyer_multiple(recipients)