示例#1
0
    def set_projects_start(self):
        notifications = []

        projects = Project.objects.filter(
            Q(from_date=self.tomorrow)
            | Q(from_date=self.next_week)).select_related(
                'manager_info', 'client')

        for project in projects:
            user_ids = []

            dev_id = list(
                Developer.objects.filter(project=project).values_list(
                    'id', flat=True))
            manager_id = project.manager_info.id
            client_id = project.client.id

            user_ids += dev_id
            user_ids.append(manager_id)
            user_ids.append(client_id)

            users = User.objects.filter(id__in=user_ids)

            for user in users:
                self.fields['user'] = user
                self.fields[
                    'title'] = f"Start of project {project.project_name}!"
                self.fields[
                    'description'] = f"Project {project.project_name} starts on {project.project_started_date}"
                self.fields['type_notice'] = 'START_PROJECT'

                notifications.append(Notification(**self.fields))
        Notification.objects.bulk_create(notifications)
示例#2
0
    def get_redirect_url(self, *args, **kwargs):
        authorization = get_object_or_404(PublicAuthorization,
                                          hash_id=kwargs['hash'])
        public_group = authorization.group
        public_group.group_status = 'in_progress'
        notification = Notification()
        notification.user = public_group.document.owner
        if authorization.closing_date:
            public_group.closing_date = authorization.closing_date
            document = Document.objects.get(id=authorization.group.document.id)
            document.responsible = authorization.congressman
            document.save()
            notification.message = _('%s accepted your request to change the \
            end date') % (authorization.congressman.name.title())
        else:
            notification.message = _('%s accepted your request to make the \
                document public') % (authorization.congressman.name.title())
            public_group.openning_date = datetime.now()
        notification.save()
        public_group.save()

        return reverse('project',
                       kwargs={
                           'id': public_group.id,
                           'documment_slug': public_group.document.slug
                       })
def _send_webpush(token: str, subscription_object: dict, notification: Notification):
    return webpush(
        subscription_object,
        data=json.dumps(
            {
                'title': str(_('Genkai - смотреть аниме онлайн')),
                'text': notification.get_push_notification_text(),
                'url': notification.get_push_notification_url(),
                'notification': NotificationSerializer(notification).data,
                'notifications_count': notification.user.get_not_seen_notifications_count(),
            }
        ),
        vapid_private_key=settings.PUSH_NOTIFICATIONS_PRIVATE_KEY,
        headers={
            'Authorization': f'WebPush {token}',
            'Crypto-Key': f'p256ecdsa={settings.PUSH_NOTIFICATIONS_BASE64_PUBLIC_KEY}',
        },
    )
示例#4
0
    def post(self, request, *args, **kwargs):
        current_user = self.request.user
        current_user_profile = current_user.profile
        current_event = Event.objects.get(id=self.kwargs['pk'])
        users_to_add_ids = request.data[
            'users']  # will be profile id, not user id

        if current_user_profile in current_event.participants.all(
        ) or current_user_profile in current_event.cohosts.all(
        ) or current_user_profile == current_event.admin:
            initiator_filter = Q(initiator=current_user_profile)
            recipient_filter = Q(recipient=current_user_profile)
            accepted_filter = Q(accepted=True)
            current_user_connections = [
                item for item in ConnectionRequest.objects.filter(
                    initiator_filter
                    & accepted_filter).values_list('recipient__id', flat=True)
            ]
            current_user_connections = current_user_connections + [
                item for item in ConnectionRequest.objects.filter(
                    recipient_filter
                    & accepted_filter).values_list('initiator_id', flat=True)
            ]

            user_ids_successfully_added = []
            for user_id in users_to_add_ids:
                user_id_int = int(user_id)
                if user_id_int in current_user_connections:
                    user_to_add_profile = UserProfile.objects.get(
                        id=user_id_int)
                    current_event.invited.add(user_to_add_profile)
                    user_ids_successfully_added.append(user_id_int)
            if len(user_ids_successfully_added) > 0:
                new_notification = Notification(
                    content_type=ContentType.objects.get_for_model(Event),
                    object_id=current_event.id)
                new_notification.save()
                new_notification.recipient_users.set(
                    user_ids_successfully_added)
            return Response({"code": "success"})
        else:
            return Response({"code": "failure"})
    def content_type(self, request, *args, **kwargs):
        """
        Returns response wit a list of serialized ContentType instances that
        are associated with at least one notification action object.

        :param request: the request instance.
        :rtype: rest_framework.response.Response.
        """
        content_types   = Notification.get_content_types()
        serializer      = ContentTypeSerializer(content_types, many=True)

        return Response(serializer.data)
示例#6
0
    def get_redirect_url(self, *args, **kwargs):
        feedback_authorization = get_object_or_404(FeedbackAuthorization,
                                                   hash_id=kwargs['hash'])

        if feedback_authorization.group.group_status == 'waiting_feedback':
            document = feedback_authorization.group.document

            public_group = feedback_authorization.group
            public_group.group_status = 'analyzing'
            public_group.save()

            notification = Notification()
            notification.user = document.owner
            proposal_title = format_proposal_title(document)

            message = _('{} accepted your request for final version of \
            proposal {}. The management will audit it.')
            notification.message = message.format(
                document.responsible.name.title(), proposal_title)
            notification.save()

            send_feedback_authorization_management(feedback_authorization)
            send_feedback_authorization_owner_document(feedback_authorization)
            messages.success(
                self.request,
                _('''The system management will audit the video
                and document information. Wait please!'''))

            return reverse('home')

        else:
            raise Http404
示例#7
0
 def handle(self, *args, **options):
     today = datetime.now().date()
     for group in InvitedGroup.objects.all():
         message = ''
         delta = group.closing_date - today
         if group.public_participation:
             if group.closing_date == today:
                 message = 'A consulta pública do documento %s encerra \
                     hoje, para prorrogar o prazo, altere a data de \
                     encerramento.' % group.document.title
             elif delta.days == -1:
                 message = 'A consulta pública do documento %s \
                     encerrou.' % group.document.title
             elif delta.days == 3:
                 message = 'A consulta pública do documento %s encerra \
                     em 3 dias, para prorrogar o prazo, altere a data de \
                     encerramento.' % group.document.title
         else:
             if group.closing_date == today:
                 message = 'A participação do grupo %s encerra \
                     hoje, para prorrogar o prazo, altere a data de \
                     encerramento.' % group.thematic_group.name
             elif delta.days == -1:
                 message = 'A participação do grupo %s \
                     encerrou.' % group.thematic_group.name
             elif delta.days == 3:
                 message = 'A participação do grupo %s encerra \
                     em 3 dias, para prorrogar o prazo, altere a data de \
                     encerramento.' % group.thematic_group.name
         if message:
             notification = Notification()
             notification.message = message
             notification.user = group.document.owner
             notification.save()
示例#8
0
    def get_redirect_url(self, *args, **kwargs):
        feedback_authorization = get_object_or_404(FeedbackAuthorization,
                                                   hash_id=kwargs['hash'])
        if feedback_authorization.group.group_status == 'waiting_feedback':
            document = feedback_authorization.group.document
            notification = Notification()
            notification.user = document.owner

            proposal_title = format_proposal_title(document)

            feedback_authorization.delete()

            message = _('{} did not accept your request for final version of \
                        proposal {}.')
            notification.message = message.format(
                document.responsible.name.title(), proposal_title)

            notification.save()
            send_feedback_unauthorization_owner_document(
                feedback_authorization)
            messages.info(self.request, _('The feedback was rejected!'))

            return reverse('home')

        else:
            raise Http404
示例#9
0
    def get_redirect_url(self, *args, **kwargs):
        authorization = get_object_or_404(PublicAuthorization,
                                          hash_id=kwargs['hash'])
        public_group = authorization.group
        document = public_group.document
        updated = self.request.GET.get('updated', False)

        if public_group.group_status != 'in_progress':
            if updated:
                message = _(
                    '{} did not accept your request to change end date \
                    of the public consultation of the proposition {}.')
            else:
                public_group.delete()
                message = _('{} did not accept your request for public \
                participation of the proposition {}.')

            notification = Notification()
            notification.user = document.owner

            proposal_title = format_proposal_title(document)

            notification.message = message.format(
                authorization.congressman.name.title(), proposal_title)

            notification.save()

            return reverse('home')
        else:
            raise Http404
示例#10
0
    def get_redirect_url(self, *args, **kwargs):
        feedback_authorization = get_object_or_404(FeedbackAuthorization,
                                                   hash_id=kwargs['hash'])
        if feedback_authorization.group.group_status == 'analyzing':
            document = feedback_authorization.group.document
            notification = Notification()
            notification.user = document.owner

            proposal_title = format_proposal_title(document)

            feedback_authorization.delete()

            message = _('The management refused the feedback of proposal {}, \
            contat us for more information.')

            notification.message = message.format(proposal_title)

            notification.save()
            send_management_unauthorization(feedback_authorization)
            messages.info(self.request, _('The feedback was rejected!'))

            return reverse('home')

        else:
            raise Http404
示例#11
0
文件: forms.py 项目: joopea/JClub
    def save(self, *args, **kwargs):
        post = PostDataView.by_id(self.cleaned_data.get('post', 0))
        creator_id = self.cleaned_data.get('author', 0)

        # store the post on all walls of all ppl that are following this user
        # followers_walls = FollowersWallDataView.list(user_id=creator_id)
        followers = FollowUserDataView.followers(creator_id)
        notifications = []
        for follower in followers:
            wall_form = WallForm(data={
                'post': post.id,
                'author': follower.author_id
            })
            if wall_form.is_valid(
            ):  # If not, this means the post is already present on the wall
                wall_form.save()  # Put the post on the wall

                notifications.append(
                    Notification(subject=Notification.SHARE_POST,
                                 owner_id=follower.author_id,
                                 author_id=creator_id,
                                 relation_1=post.pk))

        # add to own wall
        wall_form = WallForm(data={'post': post.id, 'author': creator_id})
        if wall_form.is_valid():
            wall_form.save()

            notifications.append(
                Notification(subject=Notification.FOLLOWEE_SHARE_POST,
                             owner=post.author,
                             author_id=creator_id,
                             relation_1=post.pk))

        Notification.objects.bulk_create(notifications)

        PostShareCount.update(post)
示例#12
0
def closed_participation_notify(public_group, proposal_title):
    document = public_group.document
    notification = Notification()
    notification.user = document.owner
    message = 'A sua consulta pública sobre o proposição legislativa "{}"  \
               encontra-se encerrada'

    notification.message = message.format(proposal_title)
    notification.save()
示例#13
0
    def set_birthdays(self):
        notifications = []
        users_birthdays = User.objects.filter(
            Q(birthday_date=self.tomorrow) | Q(birthday_date=self.next_week))

        for user in self.users_all:
            for birthday in users_birthdays:
                if user is birthday:
                    continue

                self.fields['user'] = user
                self.fields['title'] = f"{birthday.first_name}'s birthday!"
                self.fields['description'] = f"{birthday.last_name} {birthday.first_name}'s birthday will be on " \
                    f"{birthday.birthday_date}"
                self.fields['type_notice'] = 'BIRTHDAY'

                notifications.append(Notification(**self.fields))
        Notification.objects.bulk_create(notifications)
示例#14
0
    def set_vacations(self):
        notifications = []
        vacations = Vacation.objects.filter(
            Q(from_date=self.tomorrow) | Q(from_date=self.next_week))

        for user in self.users_all:
            for vacation in vacations:
                if user is vacations.user:
                    continue

                self.fields['user'] = user
                self.fields[
                    'title'] = f"{vacation.user.first_name}'s vacation!"
                self.fields['description'] = f"{vacation.user.last_name} {vacation.user.first_name}'s vacation starts " \
                    f"on {vacation.from_date}"
                self.fields['type_notice'] = 'VACATION'

                notifications.append(Notification(**self.fields))
        Notification.objects.bulk_create(notifications)
示例#15
0
def update_added_episodes_signal(action, pk_set, **kwargs):
    if action == 'post_add':
        notifications = []
        for episode in Episode.objects.filter(pk__in=pk_set):
            users_to_notify = User.objects.filter(
                subscription__translator=episode.translation.translator,
                subscription__title=episode.translation.title,
            )
            for user in users_to_notify:
                notifications.append(
                    Notification(
                        user=user,
                        type=Notification.TYPES.subscription,
                        episode=episode,
                    ))
        Notification.objects.bulk_create(notifications)

        for notification in notifications:
            send_push_notification_task.delay(notification.id)
示例#16
0
    def post(self, request, *args, **kwargs):
        current_user = self.request.user
        current_group = UserCreatedGroup.objects.get(id=self.kwargs['pk'])
        user_to_add_id = int(
            request.data['user'])  # will be profile id, not user id
        user_to_add = UserProfile.objects.get(id=user_to_add_id)

        if user_to_add in current_group.supplicants.all():
            if current_group.join_mode == JoinMode.MCA.value and current_user in current_group.group.user_set.all(
            ):
                current_group.group.user_set.add(user_to_add.user)
                current_group.supplicants.remove(user_to_add)

                new_notification = Notification(
                    content_type=ContentType.objects.get_for_model(
                        UserCreatedGroup),
                    object_id=current_group.id)
                new_notification.recipient_users.set((user_to_add, ))
                new_notification.save()

                return Response({"code": "success"})
            else:
                if current_user.profile in current_group.admins.all():
                    current_group.group.user_set.add(user_to_add.user)
                    current_group.supplicants.remove(current_user)

                    new_notification = Notification(
                        content_type=ContentType.objects.get_for_model(
                            UserCreatedGroup),
                        object_id=current_group.id)
                    new_notification.recipient_users.set((user_to_add, ))
                    new_notification.save()

                    return Response({"code": "success"})
                else:
                    return Response({"code": "failure"})
        else:
            return Response({"code": "failure"})
示例#17
0
    def get_redirect_url(self, *args, **kwargs):
        feedback_authorization = get_object_or_404(FeedbackAuthorization,
                                                   hash_id=kwargs['hash'])

        if feedback_authorization.group.group_status == 'analyzing':
            document = feedback_authorization.group.document

            public_group = feedback_authorization.group
            public_group.final_version = feedback_authorization.version
            public_group.group_status = 'finished'
            public_group.save()

            if feedback_authorization.video_id:
                video = DocumentVideo(document=document,
                                      video_id=feedback_authorization.video_id,
                                      title=_('Vídeo feedback'))
                video.save()

            notification = Notification()
            notification.user = document.owner
            proposal_title = format_proposal_title(document)

            message = _('The management accepted feedback of proposal {}.')
            notification.message = message.format(
                document.responsible.name.title(), proposal_title)
            notification.save()

            send_management_authorization(feedback_authorization)
            messages.success(self.request,
                             _('The feeback participation was approved!'))

            self.send_emails_from_participations(public_group)

            return reverse('home')

        else:
            raise Http404
示例#18
0
 def save(self, *args, **kwargs):
     instance = super(WithFollowNotification, self).save(*args, **kwargs)
     notification = Notification(**self.get_notification_data(instance))
     notification.save()
     return instance
示例#19
0
    def get_redirect_url(self, *args, **kwargs):
        invitation = get_object_or_404(ParcipantInvitation, pk=kwargs['pk'])
        invitation.answered = True

        if kwargs['accept'] == 'accepted':
            invitation.accepted = True
            notification = Notification()
            notification.user = invitation.group.document.owner
            participant = User.objects.get(email=invitation.email)
            notification.message = '%s aceitou o convite para participar do \
                                    grupo %s' % (participant.get_full_name(
            ), invitation.group.thematic_group.name)
            notification.save()
        elif kwargs['accept'] == 'declined':
            invitation.accepted = False
            notification = Notification()
            notification.user = invitation.group.document.owner
            participant = User.objects.get(email=invitation.email)
            notification.message = '%s não aceitou o convite para participar \
                                    do grupo %s' % (participant.get_full_name(
            ), invitation.group.thematic_group.name)
            notification.save()
        else:
            raise Http404

        invitation.save()

        return reverse('project',
                       kwargs={
                           'id': invitation.group.id,
                           'documment_slug': invitation.group.document.slug
                       })