Beispiel #1
0
    def create_message(self, session_code, data: MessageSerializer.data):
        if self.is_user_exists(
                self.user) and self.is_session_exists(session_code):
            session = Session.objects.get(code=session_code)
            user = User.objects.get(username=self.user)

            new_data = copy.deepcopy(data)
            new_data["session"] = session.id
            new_data["user"] = user.id

            serializer = MessageSerializer(data=new_data)
            serializer.is_valid(raise_exception=True)
            serializer.save()

            notif_args = {
                'source': user,
                'source_display_name': user.get_full_name(),
                'category': 'chat',
                'action': 'Sent',
                'obj': session.id,
                'short_description': 'You have a new message',
                'silent': True,
                'extra_data': {
                    notifs_settings.NOTIFICATIONS_WEBSOCKET_URL_PARAM:
                    str(session.code),
                    'message':
                    serializer.data
                }
            }

            notify(**notif_args, channels=['websocket'])

            return serializer.data
Beispiel #2
0
    def form_valid(self, form):
        form.instance.inventory = get_object_or_404(
            Inventory, loans=True, name__iexact=self.kwargs['inv'])

        response = super().form_valid(form)

        notify_bulk(
            Member.users_with_perm(PERMS.inventory.view_loan),
            NotifType.LOAN_REQUESTS,
            f"A new loan has been requested for {form.instance.requester.username} by {self.request.user.username}.",
            reverse('inventory:loan_detail',
                    kwargs={
                        'inv': self.object.inventory.canonical_(),
                        'pk': self.object.id
                    }),
            merge_key=self.object.id)

        notify(
            form.instance.requester, NotifType.LOAN_REQUESTS,
            f"A loan request has been created for you by {self.request.user.username}.",
            reverse('inventory:loan_detail',
                    kwargs={
                        'inv': self.object.inventory.canonical_(),
                        'pk': self.object.id
                    }))

        return response
Beispiel #3
0
def comment(request, pk):
    """Detail comment."""
    comment = get_object_or_404(Comment, pk=pk)
    if request.method == 'POST':
        if request.user.pk == 2:
            form = DavidReplyForm(request.POST)
        else:
            form = AdminReplyForm(request.POST)
        if form.is_valid():
            # save reply
            reply = form.save(commit=False)
            reply.comment = comment
            reply.save()
            # add rep
            add_rep(request, rp=reply)
            # create notification
            notify(reply=reply)
            messages.success(request, 'Reply created')
            return HttpResponseRedirect(reverse(
                'admins.views.comment', args=[comment.pk]))
    else:
        if request.user.pk == 2:
            form = DavidReplyForm()
        else:
            form = AdminReplyForm()
    d = {
        'comment': comment,
        'comment_pk': comment.pk,
        'form': form,
        'title': 'Comment: Add Reply',
    }
    return render_to_response('admins/detail_comment.html', 
        add_csrf(request, d), context_instance=RequestContext(request))
Beispiel #4
0
    def post(self, request, *args, **kwargs):
        """create a new message in a chat session."""
        uri = kwargs['uri']
        message = request.data['message']

        user = request.user
        chat_session = ChatSession.objects.get(uri=uri)

        chat_session_message = ChatSessionMessage.objects.create(
            user=user, chat_session=chat_session, message=message
        )

        notif_args = {
            'source': user,
            'source_display_name': user.get_full_name(),
            'category': 'chat', 'action': 'Sent',
            'obj': chat_session_message.id,
            'short_description': 'You a new message', 'silent': True,
            'extra_data': {
                notifs_settings.NOTIFICATIONS_WEBSOCKET_URL_PARAM:
                chat_session.uri,
                'message': chat_session_message.to_json()
            }
        }
        notify(**notif_args, channels=['websocket'])

        return Response({
            'status': 'SUCCESS', 'uri': chat_session.uri, 'message': message,
            'user': deserialize_user(user)
        })
Beispiel #5
0
def note(request, pk):
    """Detail note."""
    note = get_object_or_404(Note, pk=pk)
    if request.method == 'POST':
        if request.user.pk == 2:
            form = DavidCommentForm(request.POST)
        else:
            form = AdminCommentForm(request.POST)
        if form.is_valid():
            # save comment
            comment = form.save(commit=False)
            comment.note = note
            comment.save()
            # add rep
            add_rep(request, c=comment)
            # create notification
            notify(comment=comment)
            messages.success(request, 'Comment created')
            return HttpResponseRedirect(reverse(
                'admins.views.note', args=[note.pk]))
    else:
        if request.user.pk == 2:
            form = DavidCommentForm(request.POST)
        else:
            form = AdminCommentForm()
    d = {
        'form': form,
        'note': note,
        'note_pk': note.pk,
        'title': 'Note: Add Comment',
    }
    return render_to_response('admins/detail_note.html', 
        add_csrf(request, d), context_instance=RequestContext(request))
Beispiel #6
0
def new(request, pk):
    note = get_object_or_404(Note, pk=pk)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.note = note
            comment.user = request.user
            comment.save()
            # add rep
            add_rep(request, c=comment)
            # create notification
            notify(comment=comment)
            d = {
                    'comment': comment,
                    'comment_form': CommentForm(),
                    'note': note,
                    'reply_form': ReplyForm(),
                    'static': settings.STATIC_URL,
            }
            comment_form = loader.get_template('comments/comment_form.html')
            comment_temp = loader.get_template('comments/comment.html')
            context = RequestContext(request, add_csrf(request, d))
            data = {
                        'comment': comment_temp.render(context),
                        'comment_count': note.comment_count(),
                        'comment_form': comment_form.render(context),
                        'comment_pk': comment.pk,
                        'note_pk': note.pk,
            }
            return HttpResponse(json.dumps(data), mimetype='application/json')
    return HttpResponseRedirect(reverse('readings.views.detail', 
        args=[reading.slug]))
Beispiel #7
0
def new(request, pk):
    """Create new reply."""
    comment = get_object_or_404(Comment, pk=pk)
    if request.method == 'POST':
        form = ReplyForm(request.POST)
        if form.is_valid():
            reply = form.save(commit=False)
            reply.comment = comment
            reply.user = request.user
            reply.save()
            # add rep
            add_rep(request, rp=reply)
            # create notification
            notify(reply=reply)
            d = {
                    'comment': comment,
                    'reply': reply,
                    'reply_form': ReplyForm(),
                    'static': settings.STATIC_URL,
            }
            reply_form = loader.get_template('replies/reply_form.html')
            reply_temp = loader.get_template('replies/reply.html')
            context = RequestContext(request, add_csrf(request, d))
            data = {
                        'comment_pk': comment.pk,
                        'reply': reply_temp.render(context),
                        'reply_count': comment.reply_count(),
                        'reply_form': reply_form.render(context),
                        'reply_pk': reply.pk,
            }
            return HttpResponse(json.dumps(data), mimetype='application/json')
    return HttpResponseRedirect(reverse('readings.views.detail', 
        args=[comment.note.reading.slug]))
Beispiel #8
0
    def form_valid(self, form):
        """
        body=form.cleaned_data['body'],
        author=request.user.member,
        pub_date=timezone.now(),
        thread=thread,
        """
        thread = Thread.objects.get(id=self.kwargs['thread'])

        form.instance.author = self.request.user.member
        form.instance.pub_date = timezone.now()
        form.instance.thread = thread
        response = super().form_valid(form)
        # Create Notifications
        url = reverse('forum:viewthread',
                      kwargs={'thread': self.kwargs['thread']
                              }) + "#response-" + str(form.instance.id)
        for author in thread.subscribed.all():
            if author != self.request.user.member:
                notify(
                    author, NotifType.FORUM_REPLY,
                    '{} replied to a thread you\'ve subscribed to!'.format(
                        self.request.user.username), url, thread.id)
        if self.request.user.member not in thread.subscribed.all():
            thread.subscribed.add(self.request.user.member)
        return response
Beispiel #9
0
 def post(self, *args, **kwargs):
     kicked = User.objects.get(
         member__id=self.request.POST.get('user-to-remove')).member
     self.rpg.members.remove(kicked)
     notify(kicked, NotifType.RPG_KICK,
            'You were kicked from the game "{}".'.format(self.rpg.title),
            reverse('rpgs:detail', kwargs={'pk': self.kwargs['pk']}))
     add_message(self.request, messages.SUCCESS,
                 "{} Removed from Event".format(kicked.equiv_user.username))
     return HttpResponseRedirect(reverse('rpgs:detail', kwargs={'pk': self.kwargs['pk']}))
Beispiel #10
0
def follow(request, slug):
    """Follow or unfollow a user."""
    user = user_exists(slug)
    change_count = 1
    # if request method is POST and
    # the follow/unfollow user is not the current user
    if request.method == 'POST' and user.pk != request.user.pk:
        # if request POST has follow in it
        if request.POST.get('follow'):
            # follow user
            follow = user.followed_set.create(follower=request.user)
            # add rep
            add_rep(request, fw=follow)
            # create notification
            notify(follow=follow)
        # if request POST has unfollow in it
        elif request.POST.get('unfollow'):
            # unfollow user
            follow = user.followed_set.filter(follower=request.user)[0]
            # del rep
            del_rep(request, fw=follow)
            follow.delete()
        # if current user is on another user's page
        if user.pk == int(request.POST.get('current_pk', 0)):
            followers_count = str(user.profile.followers_count())
            following_count = str(user.profile.following_count())
        # if current user is on their own page
        elif request.user.pk == int(request.POST.get('current_pk', 0)):
            followers_count = str(request.user.profile.followers_count())
            following_count = str(request.user.profile.following_count())
        # if current user is not on anyone's page
        else:
            followers_count = 0
            following_count = 0
            change_count = 0
        d = {
                'current_pk': request.POST.get('current_pk'),
                'profile_user': user,
        }
        t = loader.get_template('follows/follow_form.html')
        c = RequestContext(request, add_csrf(request, d))
        data = { 
                    'change_count': change_count,
                    'follow_form': t.render(c),
                    'followers_count': followers_count,
                    'following_count': following_count,
                    'user_id': str(user.pk),
        }
        return HttpResponse(json.dumps(data), mimetype='application/json')
    else:
        return HttpResponseRedirect(reverse('readings.views.list_user', 
            args=[profile.slug]))
Beispiel #11
0
def authoriseLoan(request, pk):
    item = get_object_or_404(Loan, pk=pk)
    item.authorised = request.user.member
    item.save()
    notify(
        item.requester, NotifType.LOAN_REQUESTS,
        f"A pending loan request has been authorised.",
        reverse('inventory:loan_detail',
                kwargs={
                    'inv': item.inventory.canonical_(),
                    'pk': item.id
                }))
    return redirect(item.get_absolute_url())
Beispiel #12
0
def send_message(member, thread, message, request=None):
    # Send the notification to everyone in the thread except the sender.
    url = reverse('message:message_thread', args=[thread.id])
    for receiver in thread.participants.all():
        message_txt = 'You got a message from ' + \
            str(member.equiv_user.username)
        if thread.title:
            message_txt += ' in chat "' + str(thread.title) + '"'
        message_txt += ': ' + visible(message)
        if member != receiver:
            notify(receiver, NotifType.MESSAGE, message_txt, url)
    give_achievement_once(member, "messaged", request=request)
    return Message.objects.create(sender=member,
                                  thread=thread,
                                  content=message)
Beispiel #13
0
def new(request, slug):
    """Create new tie for reading."""
    reading = get_object_or_404(Reading, slug=slug)
    if request.method == "POST":
        # If reading has 5 tags, do not add or create
        if len(reading.tie_set.all()) >= 5:
            messages.warning(request, "Each read can only have 5 tags")
        else:
            try:
                # If user already added a tag
                user = reading.tie_set.get(user=request.user)
                messages.error(request, "You can only add 1 tag per read")
            except ObjectDoesNotExist:
                name = request.POST.get("tag_name")
                name = name.lower()
                pattern = only_letters()
                # If name contains only letters
                if re.search(pattern, name):
                    # If name does not contain any banned words
                    blacklist = banned_words()
                    if not re.search(blacklist, name):
                        try:
                            # If tag exists, get tag
                            tag = Tag.objects.get(name=name)
                        except ObjectDoesNotExist:
                            # If tag does not exist, create tag
                            tag = Tag(name=name, user=request.user)
                            tag.slug = slugify(tag.name)
                            tag.save()
                        try:
                            # Check to see if tie exists
                            tie = reading.tie_set.get(tag=tag)
                        except ObjectDoesNotExist:
                            # If tie does not exist, create it
                            tie = request.user.tie_set.create(reading=reading, tag=tag)
                            # add rep
                            add_rep(request, t=tie)
                            # create notification
                            notify(tie=tie)
                            d = {"reading": reading}
                            tags = loader.get_template("tags/tags.html")
                            context = RequestContext(request, d)
                            data = {"ties": tags.render(context)}
                            return HttpResponse(json.dumps(data), mimetype="application/json")
    return HttpResponseRedirect(reverse("readings.views.detail", args=[reading.slug]))
Beispiel #14
0
 def post(self, *args, **kwargs):
     try:
         added = User.objects.get(
             username__iexact=self.request.POST.get('username')).member
     except User.DoesNotExist:
         add_message(self.request, messages.WARNING, "Username not found")
     else:
         if self.rpg.members.count() >= self.rpg.players_wanted:
             add_message(self.request, messages.WARNING, "Game is full")
         else:
             self.rpg.members.add(added)
             notify(added, NotifType.RPG_KICK,
                    'You were added to the game "{}".'.format(
                        self.rpg.title),
                    reverse('rpgs:detail', kwargs={'pk': self.kwargs['pk']}))
             add_message(self.request, messages.SUCCESS,
                         "{} Added to Event".format(added.equiv_user.username))
     return HttpResponseRedirect(reverse('rpgs:detail', kwargs={'pk': self.kwargs['pk']}))
Beispiel #15
0
 def add_user_to_rpg(self, member, rpg, base=True):
     grammarset = namedtuple('grammarset', 'this that the This That The')
     if base:
         descriptor = "event"
         grammar = grammarset('this', 'that', 'the', 'This', 'That', 'The')
     else:
         descriptor = f"parent event ({rpg.title})"
         grammar = grammarset('a', 'a', 'a', 'A', 'A', 'A')
     if member in rpg.members.all() and base:
         add_message(self.request, messages.WARNING,
                     f"You are already in {grammar.this} {descriptor}!")
     elif member in rpg.game_masters.all() and base:
         add_message(self.request, messages.WARNING,
                     f"You are running {grammar.that} {descriptor}!")
     elif rpg.members.count() >= rpg.players_wanted:
         add_message(self.request, messages.WARNING,
                     f"Sorry, {grammar.this} {descriptor} is already full")
     elif not member.is_soc_member and rpg.member_only:
         add_message(self.request, messages.WARNING, f"{grammar.This} {descriptor} is only available to current members. "
                                                     "Please verify your membership from your profile and try again.")
     elif len(member.discord.strip()) == 0 and rpg.discord:
         add_message(self.request, messages.WARNING, f"{grammar.This} {descriptor} is being held on Discord. "
                                                     "Please add a Discord account to your profile and try again.")
     elif rpg.child_signup_only and base:
         add_message(self.request, messages.WARNING, f"{grammar.This} {descriptor} requires you to sign up to a child event. "
                                                     "Please chose one from the list below and signup there.")
     else:
         if rpg.parent and (member not in rpg.parent.members.all() and member not in rpg.parent.game_masters.all() and rpg.parent.creator != member):
             # Recursively add users to the event's parents
             if not self.add_user_to_rpg(member, rpg.parent, base=False):
                 return False
         rpg.members.add(self.request.user.member)
         notify(rpg.creator, NotifType.RPG_JOIN,
                'User {} joined your game "{}"!'.format(
                    self.request.user.username, rpg.title),
                reverse('rpgs:detail', kwargs={'pk': self.kwargs['pk']}))
         if base and rpg.success_message:
             add_message(self.request, messages.SUCCESS, mark_safe(
                 parse_md_text(rpg.success_message)), extra_tags="alert-bootstrapable")
         else:
             add_message(self.request, messages.SUCCESS,
                         f"You have successfully joined {grammar.this} {descriptor}")
         return True
     return False
Beispiel #16
0
    def post(self, *args, **kwargs):
        rpg = get_object_or_404(Rpg, pk=self.kwargs['pk'])

        if self.request.user.member not in rpg.members.all():
            add_message(self.request, messages.WARNING,
                        "You are not currently in that event!")
        child = rpg.children.filter(members=self.request.user.member).first()
        if child:
            add_message(self.request, messages.WARNING, f"You are signed up to the child event {child.title}! "
                                                        "Please leave that before leaving this event.")
        else:
            rpg.members.remove(self.request.user.member)
            notify(rpg.creator, NotifType.RPG_JOIN,
                   'User {} left your game "{}"!'.format(
                       self.request.user.username, rpg.title),
                   reverse('rpgs:detail', kwargs={'pk': self.kwargs['pk']}))
            add_message(self.request, messages.SUCCESS,
                        f"You have successfully left the event {rpg.title}.")
        if rpg.published:
            return HttpResponseRedirect(reverse('rpgs:detail', kwargs={'pk': self.kwargs['pk']}))
        return HttpResponseRedirect(reverse('rpgs:index'))
Beispiel #17
0
def new(request, slug):
    """Create new note for reading."""
    reading = get_object_or_404(Reading, slug=slug)
    if request.method == 'POST':
        form = NoteForm(request.POST)
        if form.is_valid():
            note = form.save(commit=False)
            note.reading = reading
            note.user = request.user
            note.save()
            # facebook open graph add note
            facebook_graph_add_note(request.user, reading)
            # add rep
            add_rep(request, n=note)
            request.user.vote_set.create(note=note, value=1)
            notify(note=note)
            if request.user.is_staff:
                # auto create votes for reading and reading.notes
                auto_vote(request, reading)
            d = {
                    'comment_form': CommentForm(),
                    'note': note,
                    'note_form': NoteForm(),
                    'reading': reading,
                    'static': settings.STATIC_URL,
            }
            bullet_notes = loader.get_template('notes/bullet_notes.html')
            note_form = loader.get_template('notes/note_form.html')
            note_temp = loader.get_template('notes/note.html')
            context = RequestContext(request, add_csrf(request, d))
            data = {
                        'bullet_notes': bullet_notes.render(context),
                        'note': note_temp.render(context),
                        'note_form': note_form.render(context),
                        'note_pk': note.pk,
            }
            return HttpResponse(json.dumps(data), mimetype='application/json')
    return HttpResponseRedirect(reverse('readings.views.detail', 
        args=[reading.slug]))
Beispiel #18
0
def reading(request, slug):
    """Detail reading."""
    reading = get_object_or_404(Reading, slug=slug)
    if request.method == 'POST':
        if request.user.pk == 2:
            form = DavidNoteForm(request.POST)
        else:
            form = AdminNoteForm(request.POST)
        if form.is_valid():
            # save note
            note = form.save(commit=False)
            note.reading = reading
            note.save()
            # facebook open graph add note
            if note.user.pk == request.user.pk:
                facebook_graph_add_note(request.user, reading)
            # add rep
            add_rep(request, n=note)
            # create notification
            notify(note=note)
            note.user.vote_set.create(note=note, value=1)
            # auto create votes for reading and reading.notes
            auto_vote(request, reading)
            messages.success(request, 'Note created')
            return HttpResponseRedirect(reverse('admins.views.reading', 
                args=[reading.slug]))
    else:
        if request.user.pk == 2:
            form = DavidNoteForm()
        else:
            form = AdminNoteForm()
    d = {
        'form': form,
        'reading': reading,
        'title': 'Reading: Add Note',
    }
    return render_to_response('admins/detail_reading.html', 
        add_csrf(request, d), context_instance=RequestContext(request))
Beispiel #19
0
def new_reading(request, pk):
    """Create a downvote or upvote for reading."""
    reading = get_object_or_404(Reading, pk=pk)
    if request.method == 'POST' and request.POST.get('action'):
        # If user is downvoting
        if request.POST.get('action') == 'downvote':
            value = -1
        # If user is upvoting
        elif request.POST.get('action') == 'upvote':
            value = 1
        try:
            # Check to see if user already voted
            vote = reading.vote_set.get(user=request.user)
            # If user already upvoted
            if vote.value == 1:
                # If user is upvoting again, remove the vote
                if value == 1:
                    # del rep
                    del_rep(request, v=vote)
                    vote.delete()
                # If user is downvoting, downvote the note
                else:
                    vote.value = value
                    vote.save()
                    # If user changes their vote, update the notifications
                    notifications = Notification.objects.filter(vote=vote)
                    for notification in notifications:
                        notification.created = timezone.now()
                        notification.viewed = False
                        notification.save()
            # If user already downvoted
            elif vote.value == -1:
                # If user is downvoting again, remove the vote
                if value == -1:
                    # del rep
                    del_rep(request, v=vote)
                    vote.delete()
                # If user is upvoting, upvote the note
                else:
                    vote.value = value
                    vote.save()
                    # If user changes their vote, update the notifications
                    notifications = Notification.objects.filter(vote=vote)
                    for notification in notifications:
                        notification.created = timezone.now()
                        notification.viewed = False
                        notification.save()
        except ObjectDoesNotExist:
            # If the user has not yet voted, create a new vote
            vote = request.user.vote_set.create(reading=reading, value=value)
            # add rep
            add_rep(request, v=vote)
            # create notification
            notify(vote=vote)
        vote_reading_form = loader.get_template('votes/vote_reading_form.html')
        context = RequestContext(request, add_csrf(request, 
            { 'reading': reading }))
        data = {
                    'pk': reading.pk,
                    'vote_reading_form': vote_reading_form.render(context),
        }
        return HttpResponse(json.dumps(data), mimetype='application/json')
    return HttpResponseRedirect(reverse('readings.views.detail', 
        args=[reading.slug]))
Beispiel #20
0
def notify_achievement(member: Member, name: str, request):
    achiev_name = f"You got an achievement: {name}!"
    notify(member, NotifType.ACHIEVEMENTS, achiev_name,
           "/user/me/achievements/")
    if request:
        add_message(request, messages.SUCCESS, achiev_name)