Пример #1
0
def relationship_post_save_handler(created, instance, **_):
    # Only notify if this is a new *active* relationship
    if not created or not instance.is_active:
        return

    send([instance.mentor], 'new_mentee', {'relationship': instance})
    send([instance.mentee], 'new_mentor', {'relationship': instance})
Пример #2
0
def membership_callback(request, *args, **kwargs):
    html = ""
    if request.method == 'POST':
        private_key = "8620AAuGSwaBitcoin77BTCPRVYT5IhY8uakoZyYJI2B9umZBW"
        h = hashlib.sha512(private_key.encode(encoding='utf-8'))
        private_key_hash = h.hexdigest()
        if (request.POST.get('confirmed') == '0'
                and request.POST.get('box') == '8620'
                and request.POST.get('status') == 'payment_received'
                and request.POST.get('private_key_hash') == private_key_hash):
            user = User.objects.get(username=request.POST.get('user'))
            valid_thru = date.today() + relativedelta.relativedelta(months=1)
            profile = Profile.objects.filter(user=user)
            profile.update(membresia=request.POST.get('order'),
                           valid_thru=valid_thru)
            send([user], "Membership_upgraded",
                 {"valid_thru": profile[0].valid_thru})
            html = "cryptobox_newrecord"
        elif request.POST.get('confirmed') == '1':
            html = "cryptobox_updated"
        else:
            html = "cryptobox_nochanges"
    else:
        html = "Only POST Data Allowed"
    return HttpResponse(html)
Пример #3
0
def relationship_post_save_handler(created, instance, **_):
    # Only notify if this is a new *active* relationship
    if not created or not instance.is_active:
        return

    send([instance.mentor], 'new_mentee', {'relationship': instance})
    send([instance.mentee], 'new_mentor', {'relationship': instance})
Пример #4
0
def process_n12n_formset(formset, label, space, object_title='', object_link=''):
    """
    Process a filled NotificationFormset. Standalone so it can be used
    both in a class-based mixin and a functional view, keeping the codebase
    DRY.
    parameters: the formset, the notification label and the current Space.
                optionally title and link of the object to notify about
    """
    if formset.is_valid():
        if 'notify_these_members' in formset.cleaned_data[0].keys():
            users = list(formset.cleaned_data[0]['notify_these_members'])
        else:
            users = []
        role_users = {
            'all': space.get_members().user_set.all(),
            'team': space.get_team().user_set.all(),
            'admins': space.get_admins().user_set.all()
        }
        if 'notify_by_role' in formset.cleaned_data[0]:
            for role in formset.cleaned_data[0]['notify_by_role']:
                if role in role_users.keys():
                    users.extend(role_users[role])
        users = set(users) # ensure no user gets multiple mail
        #from pinax.notifications.models import NoticeType
        send(users, label, {
            'space_url':space.get_absolute_url(),
            'object_title': object_title,
            'object_link': object_link,
        })
    else:
        print(formset.errors)
Пример #5
0
def was_befriended(sender, instance, created, raw, **kwargs):
    """ Notify a user when other user befriends him """
    if notification and created and not raw:
        recipients = [instance.friend_to, ]
        extra_context = {'username': instance.friend_from,
                        'STATIC_URL': settings.STATIC_URL,}
        notification.send(recipients, "new_friend", extra_context)
Пример #6
0
 def post(self, request, *args, **kwargs):
     id = request.POST.get('id', None)
     if id is None:
         return JsonResponse({'error': 'No ID is provided.'})
     job = vatic_models.Job.objects.filter(
         id=id, group__parent__topic__owner__user=request.user).first()
     if job is None:
         return JsonResponse({'error': 'Jobs of this user are not found.'})
     annotators = Annotator.objects.all(
     )  # all annotators who has not been assigned to this job
     users = [annotator.user for annotator in annotators]
     if notification:
         try:
             notification.send(users,
                               'vatic_job_invite',
                               {'from_user': request.user},
                               scoping=job)
         except Exception as e:
             logger.debug(e)
             return JsonResponse(
                 {'error': 'Internal Server Error: {}'.format(e)})
     else:
         return JsonResponse(
             {'error': 'Cannot connect to notification app.'})
     return JsonResponse(
         {'msg': 'Invited {} annotators to the job.'.format(len(users))})
Пример #7
0
def delete(request, message_id, success_url=None):
    """
    Marks a message as deleted by sender or recipient. The message is not
    really removed from the database, because two users must delete a message
    before it's save to remove it completely.
    A cron-job should prune the database and remove old messages which are
    deleted by both users.
    As a side effect, this makes it easy to implement a trash with undelete.

    You can pass ?next=/foo/bar/ via the url to redirect the user to a different
    page (e.g. `/foo/bar/`) than ``success_url`` after deletion of the message.
    """
    user = request.user
    now = timezone.now()
    message = get_object_or_404(Message, id=message_id)
    deleted = False
    if success_url is None:
        success_url = reverse('messages_inbox')
    if 'next' in request.GET:
        success_url = request.GET['next']
    if message.sender == user:
        message.sender_deleted_at = now
        deleted = True
    if message.recipient == user:
        message.recipient_deleted_at = now
        deleted = True
    if deleted:
        message.save()
        messages.info(request, _(u"Message successfully deleted."))
        if notification:
            notification.send([user], "messages_deleted", {'message': message,})
        return HttpResponseRedirect(success_url)
    raise Http404
Пример #8
0
def undelete(request, message_id, success_url=None):
    """
    Recovers a message from trash. This is achieved by removing the
    ``(sender|recipient)_deleted_at`` from the model.
    """
    user = request.user
    message = get_object_or_404(Message, id=message_id)
    undeleted = False
    if success_url is None:
        success_url = reverse('messages_inbox')
    if 'next' in request.GET:
        success_url = request.GET['next']
    if message.sender == user:
        message.sender_deleted_at = None
        undeleted = True
    if message.recipient == user:
        message.recipient_deleted_at = None
        undeleted = True
    if undeleted:
        message.save()
        messages.info(request, _(u"Message successfully recovered."))
        if notification:
            notification.send([user], "messages_recovered", {'message': message,})
        return HttpResponseRedirect(success_url)
    raise Http404
Пример #9
0
    def get_redirect_url(self, project_slug, member_id):
        """Save Sponsor as Rejected and redirect

        :param project_slug: The slug of the parent Sponsor's parent Project
        :type project_slug: str

        :param member_id: The id of the Sponsor
        :type member_id: int

        :returns: URL
        :rtype: str
        """
        if self.request.user.is_staff:
            sponsor_qs = Sponsor.unapproved_objects.all()
        else:
            sponsor_qs = Sponsor.unapproved_objects.filter(
                Q(project__owner=self.request.user)
                | Q(project__sponsorship_managers=self.request.user))
        sponsor = get_object_or_404(sponsor_qs, id=member_id)
        sponsor.approved = False
        sponsor.rejected = True
        remarks = self.request.GET.get('remark', '')
        sponsor.remarks = remarks
        sponsor.save()
        project = Project.objects.get(slug=self.kwargs.get('project_slug'))
        sponsorship_managers = project.sponsorship_managers.all()
        send([
            self.request.user,
        ] + list(sponsorship_managers), NOTICE_SUSTAINING_MEMBER_REJECTED, {
            'remarks': remarks,
            'sustaining_member_name': sponsor.name
        })
        return reverse(self.pattern_name,
                       kwargs={'project_slug': project_slug})
Пример #10
0
def undelete(request, message_id, success_url=None):
    """
    Recovers a message from trash. This is achieved by removing the
    ``(sender|recipient)_deleted_at`` from the model.
    """
    user = request.user
    message = get_object_or_404(Message, id=message_id)
    undeleted = False
    if success_url is None:
        success_url = reverse('messages_inbox')
    if 'next' in request.GET:
        success_url = request.GET['next']
    if message.sender == user:
        message.sender_deleted_at = None
        undeleted = True
    if message.recipient == user:
        message.recipient_deleted_at = None
        undeleted = True
    if undeleted:
        message.save()
        messages.info(request, _(u"Message successfully recovered."))
        UserOnBoardNotification.objects.create(user=user, title="Nachricht", notify_typ="info",
                                               notify_message="Nachricht wurde wiederhergestellt!")
        if notification:
            notification.send([user], "messages_recovered", {'message': message, })
        return HttpResponseRedirect(success_url)
    raise Http404
Пример #11
0
def delete(request, message_id, success_url=None):
    """
    Marks a message as deleted by sender or recipient. The message is not
    really removed from the database, because two users must delete a message
    before it's save to remove it completely.
    A cron-job should prune the database and remove old messages which are
    deleted by both users.
    As a side effect, this makes it easy to implement a trash with undelete.

    You can pass ?next=/foo/bar/ via the url to redirect the user to a different
    page (e.g. `/foo/bar/`) than ``success_url`` after deletion of the message.
    """
    user = request.user
    now = timezone.now()
    message = get_object_or_404(Message, id=message_id)
    deleted = False
    if success_url is None:
        success_url = reverse('messages_inbox')
    if 'next' in request.GET:
        success_url = request.GET['next']
    if message.sender == user:
        message.sender_deleted_at = now
        deleted = True
    if message.recipient == user:
        message.recipient_deleted_at = now
        deleted = True
    if deleted:
        message.save()
        messages.info(request, _(u"Message successfully deleted."))
        if notification:
            notification.send([user], "messages_deleted", {'message': message, })
        return HttpResponseRedirect(success_url)
    raise Http404
Пример #12
0
    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance,
                                         data=request.data,
                                         partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)
        time = f"{datetime.now()}"
        if request.data.get('status'):
            if request.data['status'] == Event.QUOTATION:
                supplier = Suppliers.objects.get(id=request.tenant.id)
                user = User.objects.filter(user_type=User.ASSOCIATE_USER)
                NoticeType.create(
                    f"quotation_{instance.id}_{time[5:-7]}", _(instance.name),
                    _(instance.name + " has been changed to quotation"))
                send(user, f"quotation_{instance.id}_{time[5:-7]}",
                     {"from_user": settings.DEFAULT_FROM_EMAIL})
            if request.data['status'] == Event.CONFIRMATION:
                NoticeType.create(
                    f"confirmation_{instance.id}_{time[5:-7]}",
                    _(instance.name),
                    _(instance.name + " has been changed to confirmation"))
                send([instance.client.user],
                     f"confirmation_{instance.id}_{time[5:-7]}",
                     {"from_user": settings.DEFAULT_FROM_EMAIL})
        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}

        return Response(serializer.data)
Пример #13
0
    def reserve(self, reserved_by):
        if reserved_by == self.mentor:
            raise TransitionNotAllowed

        self.protege = reserved_by

        notifications.send([self.mentor], "reserved_meeting_slot",
                           {"meeting": self})
Пример #14
0
 def activate(self, *args, **kwargs):
     activated_user = super(SendEmailAfterActivate,
                            self).activate(*args, **kwargs)
     user = User.objects.get(username=activated_user)
     user_in_sponsor = Profile.objects.get(user=user)
     sponsor = user_in_sponsor.sponsor
     send([sponsor], "Referral_registered", {"from_user": user})
     return activated_user
def _resend_tracking_info_signals(sender, instance: Notification,
                                  created: bool, **kwargs: dict) -> None:
    if not created:
        return

    extra_context = dict(message=instance.pk)
    extra_context.update(instance.extra_context)

    notifications.send([instance.user], instance.action.label, extra_context)
Пример #16
0
def send_manual_notification(user, label, object_title='', object_link=''):
    """
    Manually send out a notification email to user
    """
    send([user], label, {
            'space_url': '',
            'object_title': object_title,
            'object_link': object_link,
        })
Пример #17
0
 def post(self, request, *args, **kwargs):
     self.form = RegistrationForm(request.POST)
     if self.form.is_valid():
         self.form.save()
         user = auth.authenticate(username=self.form.user.email, password=self.form.str_password)
         auth.login(request, user)
         send([user], 'registration')
         return HttpResponseRedirect("/accounts/personal-data-master/")
     return self.render_to_response(self.get_context(request))
Пример #18
0
    def form_valid(self, form):
        self.created_user = self.create_user(form, commit=False)
        # prevent User post_save signal from creating an Account instance
        # we want to handle that ourself.
        self.created_user._disable_account_creation = True
        self.created_user.save()
        email_address = self.create_email_address(form)
        
	if form.cleaned_data['is_org_member']:
           harvard_group=Group.objects.get(name='Harvard')
           self.created_user.groups.add(harvard_group)

        if settings.ACCOUNT_EMAIL_CONFIRMATION_REQUIRED and not email_address.verified:
            self.created_user.is_active = False
            self.created_user.save()

        if settings.ACCOUNT_APPROVAL_REQUIRED:
            self.created_user.is_active = False
            self.created_user.save()

        self.create_account(form)
        self.after_signup(form)

        if settings.ACCOUNT_APPROVAL_REQUIRED:
            # Notify site admins about the user wanting activation
            staff = auth.get_user_model().objects.filter(is_staff=True)
            notification.send(staff, "account_approve", {"from_user": self.created_user})
            return self.account_approval_required_response()
        if settings.ACCOUNT_EMAIL_CONFIRMATION_EMAIL and not email_address.verified:
            self.send_email_confirmation(email_address)

        if settings.ACCOUNT_EMAIL_CONFIRMATION_REQUIRED and not email_address.verified:
            return self.email_confirmation_required_response()
        else:
            show_message = [
                settings.ACCOUNT_EMAIL_CONFIRMATION_EMAIL,
                self.messages.get("email_confirmation_sent"),
                not email_address.verified
            ]
            if all(show_message):
                messages.add_message(
                    self.request,
                    self.messages["email_confirmation_sent"]["level"],
                    self.messages["email_confirmation_sent"]["text"].format(**{
                        "email": form.cleaned_data["email"]
                    })
                )
            # attach form to self to maintain compatibility with login_user
            # API. this should only be relied on by d-u-a and it is not a stable
            # API for site developers.
            self.form = form

            # Use autologin only when the account is active.
            if self.created_user.is_active:
                self.login_user()

        return redirect(self.get_success_url())
Пример #19
0
def handle_invite_accepted(sender, **kwargs):
    invitation = kwargs.get("invitation")
    log(user=invitation.to_user, action="INVITE_ACCEPTED", extra={})
    send([invitation.from_user],
         "invite_accepted",
         extra_context={
             "joiner": invitation.to_user.username,
             "email": invitation.to_user.email
         })
Пример #20
0
    def save(self, sender, send=True):
        recipients = self.cleaned_data['recipient']
        subject = self.cleaned_data['subject']
        body = self.cleaned_data['body']
        recipients_cleaned = []
        for r in recipients:
            if r.split("_")[0]==u"class":
                class_id = int(r.split("_")[1])
                classroom_object = Classroom.objects.get(id=class_id)
                trainers_ids = [int(trainer['id']) for trainer in classroom_object.trainers.values()]

                trainee_ids = [int(trainee.user.id) for trainee in Trainee.objects.filter(classroom_id=class_id)]
                recipients_cleaned.extend(trainers_ids)
                recipients_cleaned.extend(trainee_ids)
            else:
                user_id = int(r.split("_")[1])
                recipients_cleaned.append(user_id)
        recipients_cleaned = list(set(recipients_cleaned))
        recipients = [User.objects.get(pk=key) for key in recipients_cleaned]
        new_message = Message.objects.create(body=body, sender=sender)

        thread = Thread.objects.create(subject=subject,
                                       latest_msg=new_message,
                                       creator=sender)
        thread.all_msgs.add(new_message)

        for recipient in recipients:
            Participant.objects.create(thread=thread, user=recipient)

        (sender_part, created) = Participant.objects.get_or_create(thread=thread, user=sender)
        sender_part.replied_at = sender_part.read_at = now()
        sender_part.save()

        thread.save()  # save this last, since this updates the search index

        message_composed.send(sender=Message,
                              message=new_message,
                              recipients=recipients)

        #send notifications
        print "notification within def save: ", notification

        if send and notification:
            if sendgrid_settings.THREADED_MESSAGES_USE_SENDGRID:
                for r in recipients:
                    reply_email = create_reply_email(sendgrid_settings.THREADED_MESSAGES_ID, r, thread)
                    notification.send(recipients, "received_email",
                                        {"thread": thread,
                                         "message": new_message}, sender=sender,
                                        from_email=reply_email.get_from_email(),
                                        headers={'Reply-To': reply_email.get_reply_to_email()})
            else:
                notification.send(recipients, "received_email",
                                        {"thread": thread,
                                         "message": new_message}, sender=sender)

        return (thread, new_message)
Пример #21
0
def notify_new_letter(sender, instance, created, raw, **kw):
    if notification and isinstance(instance, Letter) and created and not raw:
        user = [instance.recipient,]
        game = instance.recipient_player.game
        extra_context = {'game': game, 'letter': instance, 'STATIC_URL': settings.STATIC_URL,}
        if game.fast:
            notification.send_now(user, "condottieri_messages_received", extra_context)
        else:
            notification.send(user, "condottieri_messages_received", extra_context)
Пример #22
0
def callback(request, *args, **kwargs):
    html = ""
    if request.method == 'POST':
        private_key = "8591AAuVNwoBitcoin77BTCPRVlBBm1YOY3rLZstduagpNFn6H"
        h = hashlib.sha512(private_key.encode(encoding='utf-8'))
        private_key_hash = h.hexdigest()
        if (request.POST.get('confirmed') == '0'
                and request.POST.get('box') == '8591'
                and request.POST.get('status') == 'payment_received'
                and request.POST.get('private_key_hash') == private_key_hash):
            user = User.objects.get(username=request.POST.get('user'))
            profile = Profile.objects.select_related('membresia').get(
                user=user)
            sponsor = Profile.objects.select_related('membresia').get(
                user=profile.sponsor)
            lista_de_numeros = []
            jugadas_pagadas = Jugada.objects.filter(
                orderID=request.POST.get('order')).select_related('pote')
            try:
                spp = SponsorsPorPote.objects.get(user=sponsor,
                                                  pote=jugadas_pagadas[0].pote)
            except ObjectDoesNotExist:
                spp = SponsorsPorPote(user=sponsor,
                                      pote=jugadas_pagadas[0].pote)

            for j in jugadas_pagadas:
                j.status = '3'
                j.fecha_jugada = timezone.now()
                j.save()
                profile.sponsor_revenue += j.pote.valor_jugada * sponsor.membresia.porcentaje_jugada
                spp.dinero_ganado += j.pote.valor_jugada * sponsor.membresia.porcentaje_jugada
                lista_de_numeros.append(j.numero)

            profile.puntos += 2 * len(jugadas_pagadas) if profile.membresia.tipo_membresia == 'Free' else \
                6 * len(jugadas_pagadas)

            sponsor.puntos += 1 * len(jugadas_pagadas) if sponsor.membresia.tipo_membresia != 'Free' else \
                3 * len(jugadas_pagadas)

            spp.save()
            profile.save()
            sponsor.save()
            send(
                [user], "Play_made", {
                    "jugadas": lista_de_numeros,
                    "monto": request.POST.get('amount'),
                    "tx": request.POST.get('tx')
                })
            html = "cryptobox_newrecord"
        elif request.POST.get('confirmed') == '1':
            html = "cryptobox_updated"
        else:
            html = "cryptobox_nochanges"
    else:
        html = "Only POST Data Allowed"
    return HttpResponse(html)
Пример #23
0
 def post(self, request, *args, **kwargs):
     self.form = RegistrationForm(request.POST)
     if self.form.is_valid():
         self.form.save()
         user = auth.authenticate(username=self.form.user.email,
                                  password=self.form.str_password)
         auth.login(request, user)
         send([user], 'registration')
         return HttpResponseRedirect("/accounts/personal-data-master/")
     return self.render_to_response(self.get_context(request))
Пример #24
0
    def save(self, sender, send=True):
        recipients = self.cleaned_data['recipient']
        subject = self.cleaned_data['subject']
        body = self.cleaned_data['body']

        recipients_cleaned = list(set(recipients))
        recipients = [User.objects.get(pk=key) for key in recipients_cleaned]
        new_message = Message.objects.create(body=body, sender=sender)

        thread = Thread.objects.create(subject=subject,
                                       latest_msg=new_message,
                                       creator=sender)
        thread.all_msgs.add(new_message)

        for recipient in recipients:
            Participant.objects.create(thread=thread, user=recipient)

        (sender_part,
         created) = Participant.objects.get_or_create(thread=thread,
                                                      user=sender)
        sender_part.replied_at = sender_part.read_at = now()
        sender_part.save()

        thread.save()  # save this last, since this updates the search index

        message_composed.send(sender=Message,
                              message=new_message,
                              recipients=recipients)

        #send notifications
        print "notification within def save: ", notification

        if send and notification:
            if sendgrid_settings.THREADED_MESSAGES_USE_SENDGRID:
                for r in recipients:
                    reply_email = create_reply_email(
                        sendgrid_settings.THREADED_MESSAGES_ID, r, thread)
                    notification.send(
                        recipients,
                        "received_email", {
                            "thread": thread,
                            "message": new_message
                        },
                        sender=sender,
                        from_email=reply_email.get_from_email(),
                        headers={'Reply-To': reply_email.get_reply_to_email()})
            else:
                notification.send(recipients,
                                  "received_email", {
                                      "thread": thread,
                                      "message": new_message
                                  },
                                  sender=sender)

        return (thread, new_message)
Пример #25
0
 def save(self, commit=True):
     """Override save to add created_by and meetup_location to the instance"""
     instance = super(AddMeetupForm, self).save(commit=False)
     instance.created_by = SystersUser.objects.get(user=self.created_by)
     instance.meetup_location = self.meetup_location
     members = [systers_user.user for systers_user in self.meetup_location.members.all()]
     if commit:
         instance.save()
         notification.send(members, 'new_meetup', {'meetup_location': self.meetup_location,
                           'meetup': instance})
     return instance
Пример #26
0
 def save(self, commit=True):
     """Override save to add created_by and meetup_location to the instance"""
     instance = super(AddMeetupForm, self).save(commit=False)
     instance.created_by = SystersUser.objects.get(user=self.created_by)
     instance.meetup_location = self.meetup_location
     members = [systers_user.user for systers_user in self.meetup_location.members.all()]
     if commit:
         instance.save()
         notification.send(members, 'new_meetup', {'meetup_location': self.meetup_location,
                           'meetup': instance})
     return instance
Пример #27
0
 def save(self, commit=True):
     """Override save to map input username to User and append it to the meetup location. Also,
      send the corresponding user the relevent notification."""
     instance = super(AddMeetupLocationMemberForm, self).save(commit=False)
     user = get_object_or_404(User, username=self.username)
     systersuser = get_object_or_404(SystersUser, user=user)
     if systersuser not in instance.members.all():
         instance.members.add(systersuser)
         notification.send([user], 'joined_meetup_location', {'meetup_location': instance})
     if commit:
         instance.save()
     return instance
Пример #28
0
 def save(self, commit=True):
     """Override save to map input username to User and append it to the meetup location. Also,
      send the corresponding user the relevent notification."""
     instance = super(AddMeetupLocationMemberForm, self).save(commit=False)
     user = get_object_or_404(User, username=self.username)
     systersuser = get_object_or_404(SystersUser, user=user)
     if systersuser not in instance.members.all():
         instance.members.add(systersuser)
         notification.send([user], 'joined_meetup_location', {'meetup_location': instance})
     if commit:
         instance.save()
     return instance
Пример #29
0
 def save(self, commit=True):
     """Override save to add admin to the instance"""
     instance = super(RequestMeetupForm, self).save(commit=False)
     instance.created_by = SystersUser.objects.get(user=self.user)
     instance.meetup_location = self.meetup_location
     moderators = [syster.user for syster in instance.meetup_location.moderators.all()]
     if commit:
         instance.save()
         notification.send(moderators, 'new_meetup_request',
                           {'meetup_location': instance.meetup_location,
                            'systersuser': instance.created_by,
                            'meetup_request': instance})
     return instance
Пример #30
0
def friend_joined_game(sender, **kwargs):
    """ Notify a user if a friend joins a game """
    if notification:
        user = sender.user
        friend_of_ids = user.friend_of.values_list('friend_from', flat=True)
        recipients = []
        for f in user.friends.all():
            if f.friend_to.id in friend_of_ids:
                recipients.append(f.friend_to)
        extra_context = {'username': sender.user.username,
                    'slug': sender.game.slug,
                    'STATIC_URL': settings.STATIC_URL,} 
        notification.send(recipients, "friend_joined", extra_context)
Пример #31
0
 def save(self, commit=True):
     """Override save to add admin to the instance"""
     instance = super(RequestMeetupForm, self).save(commit=False)
     instance.created_by = SystersUser.objects.get(user=self.user)
     instance.meetup_location = self.meetup_location
     moderators = [syster.user for syster in instance.meetup_location.moderators.all()]
     if commit:
         instance.save()
         notification.send(moderators, 'new_meetup_request',
                           {'meetup_location': instance.meetup_location,
                            'systersuser': instance.created_by,
                            'meetup_request': instance})
     return instance
Пример #32
0
 def save(self, commit=True):
     """Override save to add volunteer and meetup to the instance. Also, send notification to
      all organizers."""
     instance = super(AddSupportRequestForm, self).save(commit=False)
     instance.volunteer = SystersUser.objects.get(user=self.volunteer)
     instance.meetup = self.meetup
     moderators = [syster.user for syster in instance.meetup.meetup_location.moderators.all()]
     if commit:
         instance.save()
         notification.send(moderators, 'new_support_request',
                           {'meetup_location': instance.meetup.meetup_location,
                            'meetup': instance.meetup, 'systersuser': instance.volunteer,
                            'support_request': instance})
     return instance
Пример #33
0
 def save(self, sender, parent_msg=None):
     recipients = self.cleaned_data['recipient']
     subject = self.cleaned_data['subject']
     body = self.cleaned_data['body']
     message_list = []
     for r in recipients:
         msg = Message(
             sender=sender,
             recipient=r,
             subject=subject,
             body=body,
         )
         if parent_msg is not None:
             msg.parent_msg = parent_msg
             parent_msg.replied_at = timezone.now()
             parent_msg.save()
         msg.save()
         message_list.append(msg)
         if notification:
             if parent_msg is not None:
                 notification.send([sender], "messages_replied", {
                     'message': msg,
                 })
                 notification.send([r], "messages_reply_received", {
                     'message': msg,
                 })
             else:
                 notification.send([sender], "messages_sent", {
                     'message': msg,
                 })
                 notification.send([r], "messages_received", {
                     'message': msg,
                 })
     return message_list
Пример #34
0
 def save(self, sender, parent_msg=None):
     recipients = self.cleaned_data['recipient']
     subject = self.cleaned_data['subject']
     body = self.cleaned_data['body']
     message_list = []
     for r in recipients:
         msg = Message(
             sender=sender,
             recipient=r,
             subject=subject,
             body=body,
         )
         if parent_msg is not None:
             msg.parent_msg = parent_msg
             parent_msg.replied_at = timezone.now()
             parent_msg.save()
         msg.save()
         message_list.append(msg)
         UserOnBoardNotification.objects.create(user=r, title="Nachricht", notify_typ="info",
                                                notify_message="Hallo, " + str(
                                                    sender) + " hat Ihnen eine Nachricht zugesendet!")
         UserOnBoardNotification.objects.create(user=sender, title="Nachricht", notify_typ="info",
                                                notify_message="Ihr Nachricht wurde erfolgreich versendet!")
         if notification:
             if parent_msg is not None:
                 notification.send([sender], "messages_replied", {'message': msg, })
                 notification.send([r], "messages_reply_received", {'message': msg, })
             else:
                 notification.send([sender], "messages_sent", {'message': msg, })
                 notification.send([r], "messages_received", {'message': msg, })
     return message_list
Пример #35
0
    def save(self, sender, parent_msg=None):
        recipients = self.cleaned_data['recipient']
        subject = self.cleaned_data['subject']
        body = self.cleaned_data['body']
        message_list = []
        msg = Message(
            sender=sender,
            recipient=recipients,
            subject=subject,
            body=body,
        )
        if parent_msg is not None:
            msg.parent_msg = parent_msg
            parent_msg.replied_at = timezone.now()
            parent_msg.save()
        msg.save()
        message_list.append(msg)

        mail_subject = '{}님이 쪽지를 보냈습니다'.format(sender.nickname)
        mail_content = '{}님의 쪽지 : {}'.format(sender.nickname, body)
        # send_mail(mail_subject, mail_content, '*****@*****.**', [recipients.email])
        send_email_message_notification.delay(mail_subject, mail_content, user_pk=recipients.pk)

        if notification:
            if parent_msg is not None:
                notification.send([sender], "messages_replied", {'message': msg,})
                notification.send([r], "messages_reply_received", {'message': msg,})
            else:
                notification.send([sender], "messages_sent", {'message': msg,})
                notification.send([r], "messages_received", {'message': msg,})
        return message_list
Пример #36
0
 def save(self, commit=True):
     """Override save to add volunteer and meetup to the instance. Also, send notification to
      all organizers."""
     instance = super(AddSupportRequestForm, self).save(commit=False)
     instance.volunteer = SystersUser.objects.get(user=self.volunteer)
     instance.meetup = self.meetup
     moderators = [syster.user for syster in instance.meetup.meetup_location.moderators.all()]
     if commit:
         instance.save()
         notification.send(moderators, 'new_support_request',
                           {'meetup_location': instance.meetup.meetup_location,
                            'meetup': instance.meetup, 'systersuser': instance.volunteer,
                            'support_request': instance})
     return instance
Пример #37
0
 def save(self, sender, parent_msg=None):
     recipients = self.cleaned_data['recipient']
     subject = self.cleaned_data['subject']
     body = self.cleaned_data['body']
     message_list = []
     for r in recipients:
         msg = Message(
             sender = sender,
             recipient = r,
             subject = subject,
             body = body,
         )
         if parent_msg is not None:
             msg.parent_msg = parent_msg
             parent_msg.replied_at = timezone.now()
             parent_msg.save()
         msg.save()
         message_list.append(msg)
         if notification:
             if parent_msg is not None:
                 notification.send([sender], "messages_replied", {'message': msg,})
                 notification.send([r], "messages_reply_received", {'message': msg,})
             else:
                 notification.send([sender], "messages_sent", {'message': msg,})
                 notification.send([r], "messages_received", {'message': msg,})
     return message_list
Пример #38
0
def handle_object_liked(sender, **kwargs):
    like = kwargs.get("like")
    liker = like.sender
    cloudspotting = like.receiver
    log(user=liker,
        action="LIKED_CLOUDSPOTTING",
        extra={
            "pk": cloudspotting.pk,
        })
    send([cloudspotting.user],
         "cloudspotting_liked",
         extra_context={
             "cloud_type": cloudspotting.cloud_type,
             "liker": liker.username
         })
Пример #39
0
def addevents(request):
    if request.method == 'POST':
        form = AddEventForm(request.POST)
        registered_events = [account['title'] for account in Event.objects.values('title')]
        if form.is_valid():
            title = form.cleaned_data['title']
            if title not in registered_events:
                form.save(commit=True)
                send([User.objects.get(username="******")],"event_invite", {"from_user": User.objects.all()})
                HttpResponse("Redirecting")
                return redirect('/events/')
            else:
                return HttpResponse("Your event is already in our database :)")
        else:
            return HttpResponse("Form is not valid")
Пример #40
0
        def handler(self, instance):
            if instance.cancelled_by_mentor():
                # Send message to mentee
                notifications.send(
                    [instance.protege],
                    'cancelled_by_mentor',
                    {'meeting': instance})

            if instance.cancelled_by_protege():
                # Send message to mentor
                notifications.send(
                    [instance.mentor],
                    'cancelled_by_protege',
                    {'meeting': instance})

            instance.mentor.get_or_create_meeting()
Пример #41
0
    def save_model(self, request, obj, form, change):
        """
        Saves the message for the recipient and looks in the form instance
        for other possible recipients. Prevents duplication by excludin the
        original recipient from the list of optional recipients.

        When changing an existing message and choosing optional recipients,
        the message is effectively resent to those users.
        """
        obj.save()

        if notification:
            # Getting the appropriate notice labels for the sender and recipients.
            if obj.parent_msg is None:
                sender_label = 'messages_sent'
                recipients_label = 'messages_received'
            else:
                sender_label = 'messages_replied'
                recipients_label = 'messages_reply_received'

            # Notification for the sender.
            notification.send([obj.sender], sender_label, {
                'message': obj,
            })

        if form.cleaned_data['group'] == 'all':
            # send to all users
            recipients = User.objects.exclude(pk=obj.recipient.pk)
        else:
            # send to a group of users
            recipients = []
            group = form.cleaned_data['group']
            if group:
                group = Group.objects.get(pk=group)
                recipients.extend(
                    list(group.user_set.exclude(pk=obj.recipient.pk)))
        # create messages for all found recipients
        for user in recipients:
            obj.pk = None
            obj.recipient = user
            obj.save()

            if notification:
                # Notification for the recipient.
                notification.send([user], recipients_label, {
                    'message': obj,
                })
Пример #42
0
def send_notification(*args, **kwargs):
    """
    Interface for pinax send function.
    """
    if 'request_user' in kwargs:
        kwargs['extra_context']['request_user'] = kwargs['request_user']
        del kwargs['request_user']
    return send(*args, **kwargs)
Пример #43
0
    def cancel(self, cancelled_by):
        if cancelled_by not in [self.mentor, self.protege]:
            raise TransitionNotAllowed

        self.cancelled_by = cancelled_by

        if self.cancelled_by_mentor():
            # Send message to mentee
            notifications.send([self.protege], "cancelled_by_mentor",
                               {"meeting": self})

        if self.cancelled_by_protege():
            # Send message to mentor
            notifications.send([self.mentor], "cancelled_by_protege",
                               {"meeting": self})

        self.mentor.get_or_create_meeting()
Пример #44
0
def comment_saved(sender, instance, created, **kwargs):
    mentor = instance.content_object.mentor
    protege = instance.content_object.protege
    meeting_url = instance.content_object.get_url_with_domain()

    if instance.user == mentor:
        recipient = protege

    elif instance.user == protege:
        recipient = mentor

    if created and recipient:
        notifications.send(
            [recipient],
            "comment",
            {"comment": instance, "recipient": recipient, "meeting_url": meeting_url},
        )
    def save(self, sender, send=True):
        recipients = self.cleaned_data['recipient']
        subject = self.cleaned_data['subject']
        body = self.cleaned_data['body']

        recipients_cleaned = list(set(recipients))
        recipients = [User.objects.get(pk=key) for key in recipients_cleaned]
        new_message = Message.objects.create(body=body, sender=sender)

        thread = Thread.objects.create(subject=subject,
                                       latest_msg=new_message,
                                       creator=sender)
        thread.all_msgs.add(new_message)

        for recipient in recipients:
            Participant.objects.create(thread=thread, user=recipient)

        (sender_part, created) = Participant.objects.get_or_create(thread=thread, user=sender)
        sender_part.replied_at = sender_part.read_at = now()
        sender_part.save()

        thread.save()  # save this last, since this updates the search index

        message_composed.send(sender=Message,
                              message=new_message,
                              recipients=recipients)

        #send notifications
        print "notification within def save: ", notification

        if send and notification:
            if sendgrid_settings.THREADED_MESSAGES_USE_SENDGRID:
                for r in recipients:
                    reply_email = create_reply_email(sendgrid_settings.THREADED_MESSAGES_ID, r, thread)
                    notification.send(recipients, "received_email",
                                        {"thread": thread,
                                         "message": new_message}, sender=sender,
                                        from_email=reply_email.get_from_email(),
                                        headers={'Reply-To': reply_email.get_reply_to_email()})
            else:
                notification.send(recipients, "received_email",
                                        {"thread": thread,
                                         "message": new_message}, sender=sender)

        return (thread, new_message)
Пример #46
0
def comment_saved(sender, instance, created, **kwargs):
    mentor = instance.content_object.mentor
    protege = instance.content_object.protege
    meeting_url = instance.content_object.get_url_with_domain()

    if instance.user == mentor:
        recipient = protege

    elif instance.user == protege:
        recipient = mentor

    if created and recipient:
        notifications.send(
            [recipient],
            'comment',
            {'comment': instance,
             'recipient': recipient,
             'meeting_url': meeting_url})
Пример #47
0
def send_event_status_notification(instance, request):
    """ Send notifications when Event Status is changed.
    """

    # FIXME change notificxation logic

    time = f"{datetime.now()}"
    if instance.status == Event.QUOTATION:
        # supplier = Suppliers.objects.get(id=request.tenant.id)
        user = User.objects.filter(user_type=User.ASSOCIATE_USER)
        NoticeType.create(f"quotation_{instance.id}_{time[5:-7]}",
                          _(instance.name),
                          _(instance.name + " has been changed to quotation"))
        send(user, f"quotation_{instance.id}_{time[5:-7]}",
             {"from_user": settings.DEFAULT_FROM_EMAIL})
    if request.data['status'] == Event.CONFIRMATION:
        NoticeType.create(
            f"confirmation_{instance.id}_{time[5:-7]}", _(instance.name),
            _(instance.name + " has been changed to confirmation"))
        send([instance.client.user],
             f"confirmation_{instance.id}_{time[5:-7]}",
             {"from_user": settings.DEFAULT_FROM_EMAIL})
def reply_to_thread(thread, sender, body):
    from .models import Message, Participant
    new_message = Message.objects.create(body=body, sender=sender)
    new_message.parent_msg = thread.latest_msg
    thread.latest_msg = new_message
    thread.all_msgs.add(new_message)
    thread.replied = True
    thread.save()
    new_message.save()

    recipients = []
    for participant in thread.participants.all():
        participant.deleted_at = None
        participant.save()
        if sender != participant.user:  # dont send emails to the sender!
            recipients.append(participant.user)

    sender_part = Participant.objects.get(thread=thread, user=sender)
    sender_part.replied_at = sender_part.read_at = now()
    sender_part.save()

    invalidate_count_cache(Message, new_message)

    if notification:
        for r in recipients:
            if tm_settings.THREADED_MESSAGES_USE_SENDGRID:
                reply_email = sendgrid_parse_api.utils.create_reply_email(tm_settings.THREADED_MESSAGES_ID, r, thread)
                notification.send(recipients, "received_email",
                                        {"thread": thread,
                                         "message": new_message}, sender=sender,
                                        from_email=reply_email.get_from_email(),
                                        headers={'Reply-To': reply_email.get_reply_to_email()})
            else:
                notification.send([r], "received_email",
                                    {"thread": thread,
                                     "message": new_message}, sender=sender)

    return (thread, new_message)
Пример #49
0
 def handler(self, instance):
     notifications.send(
         [instance.mentor],
         'reserved_meeting_slot',
         {'meeting': instance})
Пример #50
0
 def handler(self, instance):
     notifications.send(
         [instance.protege],
         'confirmed_meeting',
         {'meeting': instance})
Пример #51
0
def comment_notification(sender, comment=None, **kwargs):
    from django.conf import settings
    from django.contrib.auth.models import User
    from django.contrib.sites.models import Site
    from work.utils import set_user_notification_by_type
    from django.core.exceptions import ValidationError

    ct_commented = comment.content_type

    logger.info("About to send a comment related the object: "+str(ct_commented.model)) #+" name:"+str(comment.name))

    if ct_commented.model == 'membershiprequest':
        msr_creator_username = comment.content_object.requested_username

        if "pinax.notifications" in settings.INSTALLED_APPS:
            from pinax.notifications import models as notification
            users = User.objects.filter(is_staff=True) | User.objects.filter(username=msr_creator_username)

            if users:
                site_name = Site.objects.get_current().name
                domain = Site.objects.get_current().domain
                membership_url= "https://" + domain +\
                    "/work/membership-discussion/" + str(comment.content_object.id) + "/"
                notification.send(
                    users,
                    "comment_membership_request",
                    {"name": comment.name,
                    "comment": comment.comment,
                    "site_name": site_name,
                    "membership_url": membership_url,
                    "current_site": domain,
                    }
                )

    elif ct_commented.model == 'joinrequest':
        jr_creator = comment.content_object.agent.user()
        jr_managers = comment.content_object.project.agent.managers()

        if "pinax.notifications" in settings.INSTALLED_APPS:
            from pinax.notifications import models as notification

            users = []
            if jr_creator:
                users.append(jr_creator.user)

            sett = set_user_notification_by_type(jr_creator.user, "comment_join_request", True)

            for manager in jr_managers:
                if manager.user():
                    users.append(manager.user().user)

            if users:
                site_name = Site.objects.get_current().name
                domain = kwargs['request'].get_host()
                try:
                    slug = comment.content_object.project.fobi_slug
                    if settings.PROJECTS_LOGIN:
                        obj = settings.PROJECTS_LOGIN
                        for pro in obj:
                            if pro == slug:
                                site_name = comment.content_object.project.agent.name
                except:
                    pass

                joinrequest_url= "https://" + domain +\
                    "/work/project-feedback/" + str(comment.content_object.project.agent.id) +\
                    "/" + str(comment.content_object.id) + "/"
                #logger.debug("Ready to send comment notification at jr_url: "+str(joinrequest_url))
                notification.send(
                    users,
                    "comment_join_request",
                    {"name": comment.name,
                    "comment": comment.comment,
                    "site_name": comment.content_object.project.agent.nick, #site_name,
                    "joinrequest_url": joinrequest_url,
                    "jn_req": comment.content_object,
                    "current_site": domain,
                    "context_agent": comment.content_object.project.agent,
                    "request_host": domain,
                    }
                )
    else:
        logger.error("The comment is related an unknown model: "+str(ct_commented.model))
        raise ValidationError("The comment is related an unknown model: "+str(ct_commented.model))