Ejemplo n.º 1
0
def delete(request, pk):
    """Delete note."""
    note = get_object_or_404(Note, pk=pk)
    reading = note.reading
    if request.method == 'POST':
        # if delete value equals note's pk
        if request.POST.get('delete') == str(note.pk):
            # if current user created note or is staff
            if request.user.pk == note.user.pk or request.user.is_staff:
                data = defaultdict(str)
                note_count = reading.note_count()
                if note_count > 1:
                    note_pk = note.pk
                    # del rep
                    del_rep(request, n=note)
                    note.delete()
                    d = {
                            'reading': reading,
                    }
                    bullet_notes = loader.get_template(
                        'notes/bullet_notes.html')
                    context = RequestContext(request, add_csrf(request, d))
                    data = { 
                                'bullet_notes': bullet_notes.render(context),
                                'pk': note_pk,
                    }
                data['note_count'] = note_count
                return HttpResponse(json.dumps(data), 
                    mimetype='application/json')
    return HttpResponseRedirect(reverse('readings.views.detail', 
        args=[reading.slug]))
Ejemplo n.º 2
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))
Ejemplo n.º 3
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]))
Ejemplo n.º 4
0
def detail(request, slug):
    """Show messages between current user and user."""
    profile = get_object_or_404(Profile, slug=slug)
    msgs = UserMessage.objects.filter(
        Q(recipient=profile.user, sender=request.user) | Q(
            recipient=request.user, sender=profile.user)).order_by('created')
    received_messages = request.user.received_messages.filter(sender=profile.user)
    # mark all messages as viewed
    if received_messages:
        for msg in received_messages:
            msg.viewed = True
            msg.save()
    # group messages by date
    if msgs:
        dates = sorted(set([msg.date() for msg in msgs]), 
            key=lambda m: datetime.strptime(m, '%b %d, %y'))
        days = []
        for day in dates:
            usermsgs = [m for m in msgs if m.date() == day]
            days.append((day, usermsgs))
        d = {
            'days': days,
            'form': ReplyMessageForm(),
            'profile_user': profile.user,
            'title': '%s Messages' % profile.user.username,
        }
        return render_to_response('usermessages/detail.html', 
            add_csrf(request, d), context_instance=RequestContext(request))
    else:
        messages.warning(request, 'You have no messages from that user')
        return HttpResponseRedirect(reverse('usermessages.views.list'))
Ejemplo n.º 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))
Ejemplo n.º 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]))
Ejemplo n.º 7
0
def fave(request, slug):
    """Save reading to current user's favorites."""
    reading = get_object_or_404(Reading, slug=slug)
    if request.method == 'POST':
        # Check to see if user already has reading saved to favorites
        try:
            favorite = request.user.favorite_set.get(reading=reading)
            # del rep
            del_rep(request, fv=favorite)
            favorite.delete()
        # If user has not saved reading to favorites
        except ObjectDoesNotExist:
            favorite = request.user.favorite_set.create(reading=reading)
            # add rep
            add_rep(request, fv=favorite)
        d = { 
            'reading': reading,
            'static': settings.STATIC_URL,
        }
        t = loader.get_template('favorites/favorite_form.html')
        context = RequestContext(request, add_csrf(request, d))
        data = {
            'favorite_count': len(request.user.favorite_set.all()),
            'favorite_form': t.render(context),
            'pk': reading.pk,
        }
        return HttpResponse(json.dumps(data), mimetype='application/json')
    return HttpResponseRedirect(reverse('readings.views.detail', 
        args=[reading.slug]))
Ejemplo n.º 8
0
def detail(request, slug):
    """Reading detail."""
    reading = get_object_or_404(Reading, slug=slug)
    # get next and previous reading
    readings = Reading.objects.all().values("pk").order_by("pk")
    first_pk = readings[0]["pk"]
    last_pk = readings.reverse()[0]["pk"]
    next_count = reading.pk + 1
    next_read = None
    prev_count = reading.pk - 1
    prev_read = None
    # if reading is the most recent reading
    if reading.pk == last_pk:
        next_read = Reading.objects.get(pk=first_pk)
    # if reading is not the most recent reading
    else:
        while not next_read and next_count <= last_pk:
            try:
                next_read = Reading.objects.get(pk=next_count)
            except ObjectDoesNotExist:
                next_count += 1
    # if reading is the oldest reading
    if reading.pk == first_pk:
        prev_read = Reading.objects.get(pk=last_pk)
    # if reading is not the oldest reading
    else:
        while not prev_read and prev_count >= first_pk:
            try:
                prev_read = Reading.objects.get(pk=prev_count)
            except ObjectDoesNotExist:
                prev_count -= 1
    comment_form = CommentForm()
    note_form = NoteForm()
    reply_form = ReplyForm()
    if request.user.is_anonymous():
        next = reverse("readings.views.detail", args=[slug])
        request.session["next"] = next
        user_tag = None
    else:
        next = ""
        request.session.get("next", "")
        user_tag = reading.tie_set.filter(user=request.user)
    d = {
        "comment_form": comment_form,
        "form": NewMessageForm(),
        "next": next,
        "next_read": next_read,
        "note_form": note_form,
        "prev_read": prev_read,
        "reading": reading,
        "reply_form": reply_form,
        "title": reading.title,
        "user_tag": user_tag,
    }
    return render_to_response("readings/detail.html", add_csrf(request, d), context_instance=RequestContext(request))
Ejemplo n.º 9
0
def edit(request, slug):
    reading = get_object_or_404(Reading, slug=slug)
    if request.user.pk != reading.user.pk and not request.user.is_staff:
        return HttpResponseRedirect(reverse("readings.views.list_user", args=[request.user.profile.slug]))
    if request.method == "POST":
        # only save the image
        reading.image = request.POST.get("image")
        reading.save()
        messages.success(request, "Reading updated")
        return HttpResponseRedirect(reverse("readings.views.detail", args=[reading.slug]))
    d = {"form": EditReadingForm(instance=reading), "reading": reading, "title": "Edit Reading"}
    return render_to_response("readings/new.html", add_csrf(request, d), context_instance=RequestContext(request))
Ejemplo n.º 10
0
def list_user(request, slug):
    """Readings for a single user."""
    profile = get_object_or_404(Profile, slug=slug)
    user = User.objects.get(pk=profile.user_id)
    readings = Reading.objects.filter(user=user).order_by("-created")
    d = {
        "current_pk": user.pk,
        "objects": page(request, readings, 10),
        "profile_user": user,
        "title": "%s Reads" % user.first_name,
    }
    return render_to_response("readings/feed.html", add_csrf(request, d), context_instance=RequestContext(request))
Ejemplo n.º 11
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]))
Ejemplo n.º 12
0
def follow_tag(request, slug):
    """Follow or unfollow a tag."""
    tag = get_object_or_404(Tag, slug=slug)
    if request.method == 'POST':
        # If current user is already following tag
        if request.user in tag.followers():
            # delete tag follow
            tagfollow = tag.tagfollow_set.get(user=request.user)
            # del rep
            del_rep(request, tf=tagfollow)
            tagfollow.delete()
        # If current user is not following tag
        else:
            # create tag follow
            tagfollow = request.user.tagfollow_set.create(tag=tag)
            # add rep
            add_rep(request, tf=tagfollow)
        d = {
            'tag': tag,
        }
        t = loader.get_template('follows/tagfollow_form.html')
        context = RequestContext(request, add_csrf(request, d))
        data = { 
            'tagfollowers_count': tag.followers_count(),
            'tag_pk': tag.pk,
            'tagfollow_form': t.render(context),
            'topic_count': request.user.profile.topic_count(),
        }
        tie = tag.tie_set.all()[0]
        if tie:
            d = { 'tie': tie }
            t = loader.get_template('follows/tiefollow_form.html')
            context = RequestContext(request, add_csrf(request, d))
            data['tiefollow_form'] = t.render(context)
        return HttpResponse(json.dumps(data), mimetype='application/json')
    return HttpResponseRedirect(reverse('tags.views.detail', 
        args=[tag.slug]))
Ejemplo n.º 13
0
def category(request, slug, category):
    """
    Show all readings that user has commented, 
    faved, added a note, tagged, or voted on.
    """
    profile = get_object_or_404(Profile, slug=slug)
    user = profile.user
    if category == 'comments':
        if profile.comment_reply_count() == 0:
            return HttpResponseRedirect(reverse('readings.views.list_user', 
                args=[profile.slug]))
        li = [comment.note.reading for comment in user.comment_set.all()]
        li += [reply.comment.note.reading for reply in user.reply_set.all()]
        li = set(li)
        title = 'Commented'
    if category == 'favorites':
        if profile.favorite_count() == 0:
            return HttpResponseRedirect(reverse('readings.views.list_user', 
                args=[profile.slug]))
        li = set([fave.reading for fave in user.favorite_set.all()])
        title = 'Favorite'
    if category == 'notes':
        if profile.note_count() == 0:
            return HttpResponseRedirect(reverse('readings.views.list_user', 
                args=[profile.slug]))
        li = set([note.reading for note in user.note_set.all()])
        title = 'Noted'
    if category == 'tags':
        if profile.tie_count() == 0:
            return HttpResponseRedirect(reverse('readings.views.list_user', 
                args=[profile.slug]))
        li = set([tie.reading for tie in user.tie_set.all()])
        title = 'Tagged'
    if category == 'votes':
        if profile.vote_count() == 0:
            return HttpResponseRedirect(reverse('readings.views.list_user', 
                args=[profile.slug]))
        li = set([vote.note.reading for vote in user.vote_set.all()])
        title = 'Voted'
    readings = reading_sorted(li)
    d = {
            'current_pk': user.pk,
            'objects': page(request, readings, 10),
            'profile_user': user,
            'title': "%s's %s Readings" % (user.first_name, title),
    }
    return render_to_response('readings/feed.html', add_csrf(request, d), 
        context_instance=RequestContext(request))
Ejemplo n.º 14
0
def delete(request, slug):
    """Delete current user's tie tag for reading."""
    reading = get_object_or_404(Reading, slug=slug)
    if request.method == "POST":
        try:
            tie = reading.tie_set.get(user=request.user)
            if request.POST.get("delete") == str(tie.pk):
                # del rep
                del_rep(request, t=tie)
                tie.delete()
                d = {"reading": reading}
                tag_form = loader.get_template("tags/tag_form.html")
                context = RequestContext(request, add_csrf(request, d))
                data = {"tag_form": tag_form.render(context), "tie_id": request.POST.get("delete")}
                return HttpResponse(json.dumps(data), mimetype="application/json")
        except ObjectDoesNotExist:
            messages.error(request, "You have not added a tag to this read")
    return HttpResponseRedirect(reverse("readings.views.detail", args=[reading.slug]))
Ejemplo n.º 15
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]))
Ejemplo n.º 16
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))
Ejemplo n.º 17
0
def new(request):
    """Login page."""
    if request.method == "POST":
        email = request.POST.get("email", "").lower()
        password = request.POST.get("password")
        user = authenticate(email=email, password=password)
        if user is not None and user.is_active:
            auth.login(request, user)
            # login url from login required
            if request.POST.get("next"):
                return HttpResponseRedirect(request.POST["next"])
            # friendly forwarding
            elif request.session.get("next"):
                next = request.session["next"]
                del request.session["next"]
                return HttpResponseRedirect(next)
            else:
                return HttpResponseRedirect(reverse("root_path"))
        else:
            messages.error(request, "The email or password you have entered is invalid")
    next = request.GET.get("next", "")
    d = {"title": "Login", "email": request.POST.get("email", ""), "next": next}
    return render_to_response("sessions/new.html", add_csrf(request, d), context_instance=RequestContext(request))
Ejemplo n.º 18
0
def new(request):
    """Add new reading."""
    NoteFormset = formset_factory(NoteForm, extra=3)
    if request.method == "POST":
        link = request.POST.get("link")
        form = ReadingForm(request.POST)
        formset = NoteFormset(request.POST)
        # if reading with link already exists, add notes to it
        try:
            reading = Reading.objects.get(link=link)
            if formset.is_valid():
                # add tag
                name = request.POST.get("tag_name")
                # if user added a tag
                if 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)
                    # if user did not add a tag, auto tag
                    else:
                        auto_tag(request, reading)
                # create notes and add it to the existing reading
                for index, note_form in enumerate(formset):
                    note = note_form.save(commit=False)
                    note.reading = reading
                    note.user = request.user
                    if note.content.strip():
                        note.save()
                        # create first vote for note
                        note.user.vote_set.create(note=note, value=1)
                        # if this is the first note
                        if index == 0:
                            # facebook open graph add note
                            facebook_graph_add_note(note.user, note.reading)
                if request.user.is_staff:
                    # auto create votes for reading and reading.notes
                    auto_vote(request, reading)
                messages.success(request, "This reading exists, your content has been added to it")
                return HttpResponseRedirect(reverse("readings.views.detail", args=[reading.slug]))
        # if reading with link does not exist, create the reading
        except ObjectDoesNotExist:
            if form.is_valid() and formset.is_valid():
                reading = form.save(commit=False)
                reading.user = request.user
                reading.save()
                # create vote for reading
                reading.vote_set.create(user=reading.user, value=1)
                # add tag
                name = request.POST.get("tag_name")
                # if user added tag
                if 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()
                            tie = request.user.tie_set.create(reading=reading, tag=tag)
                            # add rep
                            add_rep(request, t=tie)
                # if user did not add a tag, auto tag
                else:
                    auto_tag(request, reading)
                # facebook open graph add reading
                facebook_graph_add_reading(request.user, reading)
                # add rep
                add_rep(request, rd=reading)
                # create notes for this reading
                for note_form in formset:
                    note = note_form.save(commit=False)
                    note.reading = reading
                    note.user = request.user
                    if note.content.strip():
                        note.save()
                        # create first vote for note
                        request.user.vote_set.create(note=note, value=1)
                if request.user.is_staff:
                    # auto create votes for reading and reading.notes
                    auto_vote(request, reading)
                messages.success(request, "Reading created")
                return HttpResponseRedirect(reverse("readings.views.detail", args=[reading.slug]))
    else:
        form = ReadingForm()
        formset = NoteFormset()
    di = {"static": settings.STATIC_URL}
    t = loader.get_template("javascript/bookmarklet.js")
    context = RequestContext(request, di)
    d = {
        "bookmarklet": re.sub(r"\s", "%20", str(t.render(context))),
        "form": form,
        "formset": formset,
        "title": "New Reading",
    }
    return render_to_response("readings/new.html", add_csrf(request, d), context_instance=RequestContext(request))
Ejemplo n.º 19
0
def followers(request, slug):
    """Show all followers for tag."""
    tag = get_object_or_404(Tag, slug=slug)
    users = sorted([tf.user for tf in tag.tagfollow_set.all()])
    d = {"tag": tag, "title": "%s Followers" % tag.name.capitalize(), "users": users}
    return render_to_response("tags/followers.html", add_csrf(request, d), context_instance=RequestContext(request))
Ejemplo n.º 20
0
def detail(request, slug):
    """Show all readings for a single tag."""
    tag = get_object_or_404(Tag, slug=slug)
    readings = tag.readings()
    d = {"objects": page(request, readings, 10), "tag": tag, "title": "%s Reads" % tag.name.capitalize()}
    return render_to_response("readings/feed.html", add_csrf(request, d), context_instance=RequestContext(request))
Ejemplo n.º 21
0
def edit(request, slug):
    """Edit user page."""
    user = user_exists(slug)
    # Correct user
    if request.user.pk is not user.pk or not request.user.is_staff:
        return HttpResponseRedirect(reverse('readings.views.list_user', 
            args=[request.user.profile.slug]))
    profile = user.profile
    if request.method == 'POST':
        form = EditUserForm(request.POST, instance=user)
        profile_form = ProfileForm(request.POST, request.FILES, 
            instance=profile)
        if form.is_valid() and profile_form.is_valid():
            username = request.POST.get('username')
            password = request.POST.get('password1')
            # If user changed their password
            if password:
                user.set_password(password)
                user.save()
            user = form.save()
            # If an image is uploaded
            profile = profile_form.save()
            # If user changed their username
            if username:
                profile.slug = slugify(username)
                # if user has a profile image and checked clear image
                if profile.image and request.POST.get('clear_image'):
                    profile.image = ''
                    s3_delete_file(user)
                profile.save()
            if request.FILES.get('image'):
                file_path = settings.MEDIA_ROOT + '/' + profile.image.name
                try:
                    f = open(file_path)
                    f.close()
                    name = str(user.pk) + '_orig.jpg'
                    # Get absolute path of image
                    absolute_path = absolute_image_path(profile)
                    # Rename image
                    rename_image(name, absolute_path)
                    # Resize original image if too large
                    resize_orig_image(user)
                    # Create medium and small images
                    create_extra_images(user)
                    # Upload images to Amazon S3
                    s3_upload(user)
                    # Remove any old images
                    remove_images(user)
                    # Save profile image name
                    profile.image = name
                    profile.save()
                except IOError as e:
                    pass
            messages.success(request, 'User updated')
            return HttpResponseRedirect(reverse('readings.views.list_user', 
                args=[user.profile.slug]))
    else:
        form = EditUserForm(instance=user)
        profile_form = ProfileForm(instance=profile)
    d = {
            'title': 'Edit %s' % user.first_name,
            'form': form,
            'profile_form': profile_form,
    }
    return render_to_response('users/edit.html', add_csrf(request, d), 
        context_instance=RequestContext(request))
Ejemplo n.º 22
0
def new(request):
    """Create new user."""
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            user = auth.authenticate(email=request.POST.get('email').lower())
            auth.login(request, user)
            # If the user is signing up through ajax form
            pk = request.POST.get('reading')
            if pk:
                reading = get_object_or_404(Reading, pk=pk)
                # Create a dictionary of comment & vote forms for each note
                comment_forms = defaultdict(str)
                vote_forms = defaultdict(str)
                notes = reading.note_set.all()
                for note in notes:
                    d = { 
                        'comment_form': CommentForm(),
                        'note': note,
                    }
                    t = loader.get_template('comments/comment_form.html')
                    v = loader.get_template('votes/vote_form.html')
                    context = RequestContext(request, add_csrf(request, d))
                    comment_forms[str(note.pk)] = t.render(context)
                    vote_forms[str(note.pk)] = v.render(context)
                # Create a dictionary of reply forms for each comment
                reply_forms = defaultdict(str)
                comments = reading.comments()
                for comment in comments:
                    d = {
                        'comment': comment,
                        'reply_form': ReplyForm(),
                    }
                    t = loader.get_template('replies/reply_form.html')
                    context = RequestContext(request, add_csrf(request, d))
                    reply_forms[str(comment.pk)] = t.render(context)
                # Create the note & tag form
                d = {
                        'note_form': NoteForm(),
                        'reading': reading,
                        'static': settings.STATIC_URL,
                }
                favorite_form = loader.get_template('favorites/favorite_form.html')
                header = loader.get_template('header.html')
                note_form = loader.get_template('notes/note_form.html')
                tag_form = loader.get_template('tags/tag_form.html')
                context = RequestContext(request, add_csrf(request, d))
                # Ready all the partials to be outputted as JSON
                data = {
                    'comment_forms': comment_forms,
                    'favorite_form': favorite_form.render(context),
                    'header': header.render(context),
                    'note_form': note_form.render(context),
                    'reply_forms': reply_forms,
                    'success': 'yes',
                    'tag_form': tag_form.render(context),
                    'vote_forms': vote_forms,
                }
                return HttpResponse(json.dumps(data), 
                    mimetype='application/json')
            messages.success(request, 
                """Welcome %s, skim some reads and discover 
                something new""" % user.first_name)
            return HttpResponseRedirect(reverse('readings.views.discover'))
        else:
            pk = request.POST.get('reading')
            if pk:
                data = {
                    'success': 'no',
                }
                return HttpResponse(json.dumps(data), 
                    mimetype='application/json')
    else:
        form = SignUpForm()
    d = {
            'title': 'Welcome',
            'form': form,
    }
    return render_to_response('users/new.html', add_csrf(request, d), 
        context_instance=RequestContext(request))
Ejemplo n.º 23
0
def new(request):
    """Create new message."""
    if request.method == 'POST':
        form = NewMessageForm(request.POST)
        content = request.POST.get('content')
        name = request.POST.get('to')
        # if a name and content was submitted
        if content and name:
            pattern = re.compile(r'^[-A-Za-z]{2,} [-A-Za-z]{2,}$')
            # if submitted recipient name matches correct format
            if re.search(pattern, name):
                first_name, last_name = name.split()
                username = '******' % (first_name.lower().capitalize(), 
                    last_name.lower().capitalize())
                # check to see if user with that name exists
                try:
                    user = User.objects.get(username=username)
                    # create a message where current user is the snder
                    # and user is the recipient
                    message = form.save(commit=False)
                    message.recipient = user
                    message.sender = request.user
                    message.save()
                    # if replying to a message via detail page
                    if request.POST.get('reply') == '1':
                        d = {
                            'form': ReplyMessageForm(),
                            'message': message,
                            'profile_user': message.recipient,
                        }
                        message = loader.get_template(
                            'usermessages/message.html')
                        reply_message_form = loader.get_template(
                            'usermessages/reply_message_form.html')
                        context = RequestContext(request, add_csrf(request, d))
                        data = {
                            'message': message.render(context),
                            'reply_message_form': reply_message_form.render(
                                context),
                        }
                        return HttpResponse(json.dumps(data), 
                            mimetype='application/json')
                    # if creating a new message
                    else:
                        return HttpResponseRedirect(
                            reverse('usermessages.views.detail', 
                                args=[message.recipient.profile.slug]))
                # if user does not exist with that name
                except ObjectDoesNotExist:
                    messages.error(request, 'No user found')
            else:
                messages.error(request, 'What kind of name is that?')
        else:
            messages.error(request, 'Leave nothing blank')
    else:
        form = NewMessageForm()
    d = {
        'form': form,
        'title': 'New Message',
    }
    return render_to_response('usermessages/new.html', add_csrf(request, d), 
        context_instance=RequestContext(request))
Ejemplo n.º 24
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]))
Ejemplo n.º 25
0
def new_reading(request):
    """Create a new reading."""
    NoteFormset = formset_factory(NoteForm, extra=3, formset=RequiredFormSet)
    if request.method == 'POST':
        if request.user.pk == 2:
            form = DavidReadingForm(request.POST)
        else:
            form = AdminReadingForm(request.POST)
        formset = NoteFormset(request.POST)
        if form.is_valid() and formset.is_valid():
            # save reading
            reading = form.save()
            # add tag
            name = request.POST.get('tag_name')
            # if user added a tag
            if 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()
                        tie = request.user.tie_set.create(reading=reading, 
                            tag=tag)
                        # add rep
                        add_rep(request, t=tie)
            # if user did not add a tag, auto tag
            else:
                auto_tag(request, reading)
            # facebook open graph add reading
            if reading.user.pk == request.user.pk:
                facebook_graph_add_reading(request.user, reading)
            # add rep
            add_rep(request, rd=reading)
            first = True
            # save each note
            for note_form in formset:
                note = note_form.save(commit=False)
                if note.content.strip():
                    note.reading = reading
                    # if this is the first note
                    # set note.user to reading.user
                    if first:
                        note.user = reading.user
                        first = False
                    else:
                        note.user = random_user()
                    # save note
                    note.save()
                    # create first vote for note
                    note.user.vote_set.create(note=note, value=1)
                    # add rep
                    add_rep(request, n=note)
            # auto create votes for reading and reading.notes
            auto_vote(request, reading)
            messages.success(request, 'Reading created')
            return HttpResponseRedirect(reverse('admins.views.reading', 
                args=[reading.slug]))
    else:
        if request.user.pk == 2:
            form = DavidReadingForm()
        else:
            form = AdminReadingForm()
        formset = NoteFormset()
    di = { 'static': settings.STATIC_URL }
    t = loader.get_template('javascript/bookmarklet.js')
    context = RequestContext(request, di)
    d = {
        'bookmarklet': re.sub(r'\s', '%20', str(t.render(context))),
        'form': form,
        'formset': formset,
        'title': 'New Reading',
    }
    return render_to_response('readings/new.html', add_csrf(request, d), 
        context_instance=RequestContext(request))
Ejemplo n.º 26
0
def detail_show(request, slug, show, pk):
    """Reading detail."""
    if show == "comments":
        comment = get_object_or_404(Comment, pk=pk)
        a = {"comment_show": comment.note.pk, "comment_focus": comment.pk}
    elif show == "notes":
        note = get_object_or_404(Note, pk=pk)
        a = {"note_focus": note.pk}
    elif show == "replies":
        reply = get_object_or_404(Reply, pk=pk)
        a = {"comment_show": reply.comment.note.pk, "reply_focus": reply.pk, "reply_show": reply.comment.pk}
    elif show == "ties":
        tie = get_object_or_404(Tie, pk=pk)
        a = {"tie_focus": tie.pk}
    elif show == "votes":
        vote = get_object_or_404(Vote, pk=pk)
        if vote.value == 1:
            value = 1
        else:
            value = -1
        if vote.note:
            a = {"note_pk": vote.note.pk}
        elif vote.reading:
            a = {"reading_pk": vote.reading.pk}
        a["value"] = value
    reading = get_object_or_404(Reading, slug=slug)
    # get next and previous reading
    readings = Reading.objects.all().values("pk").order_by("pk")
    first_pk = readings[0]["pk"]
    last_pk = readings.reverse()[0]["pk"]
    next_count = reading.pk + 1
    next_read = None
    prev_count = reading.pk - 1
    prev_read = None
    # if reading is the most recent reading
    if reading.pk == last_pk:
        next_read = Reading.objects.get(pk=first_pk)
    # if reading is not the most recent reading
    else:
        while not next_read and next_count <= last_pk:
            try:
                next_read = Reading.objects.get(pk=next_count)
            except ObjectDoesNotExist:
                next_count += 1
    # if reading is the oldest reading
    if reading.pk == first_pk:
        prev_read = Reading.objects.get(pk=last_pk)
    # if reading is not the oldest reading
    else:
        while not prev_read and prev_count >= first_pk:
            try:
                prev_read = Reading.objects.get(pk=prev_count)
            except ObjectDoesNotExist:
                prev_count -= 1
    comment_form = CommentForm()
    note_form = NoteForm()
    reply_form = ReplyForm()
    if request.user.is_anonymous():
        user_tag = None
    else:
        user_tag = reading.tie_set.filter(user=request.user)
    b = {
        "comment_form": comment_form,
        "form": NewMessageForm(),
        "next_read": next_read,
        "note_form": note_form,
        "prev_read": prev_read,
        "reading": reading,
        "reply_form": reply_form,
        "title": reading.title,
        "user_tag": user_tag,
    }
    d = dict(a.items() + b.items())
    return render_to_response("readings/detail.html", add_csrf(request, d), context_instance=RequestContext(request))
Ejemplo n.º 27
0
def new_bookmarklet(request):
    """Create new reading from bookmarklet."""
    if request.method == "POST":
        content = request.POST.get("content", "")
        image = request.POST.get("image", "")
        link = request.POST.get("link", "")
        titl = request.POST.get("title", "")[:80]
        if request.user.is_staff:
            user_pk = request.POST.get("user")
            if user_pk:
                try:
                    user = User.objects.get(pk=int(user_pk))
                except ObjectDoesNotExist:
                    user = request.user
            else:
                user = request.user
        else:
            user = request.user
        # if there is a link and title, create reading
        if link and titl:
            try:
                # if reading with link exists, add notes to that reading
                reading = Reading.objects.get(link=link)
                reading_exists = True
            except ObjectDoesNotExist:
                reading_exists = False
                titles = Reading.objects.filter(title=titl)
                # if there is a reading with the title
                if titles:
                    titl = "%s-%s" % (titl, str(titles.count()))
                reading = Reading(image=image, link=link, title=titl, user=user)
                reading.save()
                # create vote for reading
                reading.vote_set.create(user=user, value=1)
            # add tag
            name = request.POST.get("tag_name")
            # if user added tag
            if name:
                try:
                    # check to see if user already tied a tag to this reading
                    existing_tie = reading.tie_set.get(user=user)
                # if user has not added a tag to this reading
                except ObjectDoesNotExist:
                    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=user)
                                tag.slug = slugify(tag.name)
                                tag.save()
                            tie = user.tie_set.create(reading=reading, tag=tag)
                            # add rep
                            add_rep(request, t=tie)
            # if user did not add a tag, auto tag
            else:
                auto_tag(request, reading)
            # add rep
            add_rep(request, rd=reading)
            # if there is content, create note
            if content.strip():
                note = Note(content=content, reading=reading, user=user)
                note.save()
                # create first vote for note
                user.vote_set.create(note=note, value=1)
                if reading_exists:
                    facebook_graph_add_note(note.user, note.reading)
            if not reading_exists:
                facebook_graph_add_reading(reading.user, reading)
            if request.user.is_staff:
                # auto create votes for reading and reading.notes
                auto_vote(request, reading)
            data = {"success": 1}
            return HttpResponse(json.dumps(data), mimetype="application/json")
    content = request.GET.get("note", "").lstrip(" ")
    link = request.GET.get("link", "")
    # split title
    html_title = split_title(request.GET.get("title", ""))
    if request.user.is_staff:
        if request.user.pk == 2:
            users = admin_david_list()
        else:
            users = admin_user_list()
    else:
        users = []
    d = {"content": content, "link": link, "titl": html_title, "title": "Add Reading", "users": users}
    return render_to_response(
        "readings/new_bookmarklet.html", add_csrf(request, d), context_instance=RequestContext(request)
    )