Exemple #1
0
def sign_up(request):
    """Sign up"""
    if request.method == "POST":
        userform = RegistrationForm(request.POST)
        if userform.is_valid():
            userform.save(commit=False)

            username = userform.cleaned_data['username']
            q = Q(username__iexact=username) | Q(first_name__iexact=username)
            if User.objects.filter(q).exists() or \
                len(username) < settings.ID_MIN_LENGTH or \
                    len(username) > settings.ID_MAX_LENGTH:
                errormsg = _('Please check username.')
                return error_page(request, errormsg)

            if settings.ENABLE_NICKNAME:
                nick = userform.cleaned_data['first_name']
                if nick:
                    q = Q(username__iexact=nick) | Q(first_name__iexact=nick)
                    if User.objects.filter(q).exists() or \
                        len(nick) < settings.NICKNAME_MIN_LENGTH or \
                            len(nick) > settings.NICKNAME_MAX_LENGTH:
                        errormsg = _('Please check nickname.')
                        return error_page(request, errormsg)

            code = userform.cleaned_data['code']
            email = userform.cleaned_data['email']
            signer = TimestampSigner()

            try:
                value = signer.unsign(
                    code, max_age=settings.VERIFICATION_CODE_VALID)
                code_check = value == email

                if code_check:
                    userform.save()
                    return render(
                        request,
                        "accounts/join.html",
                    )
                else:
                    errormsg = _('Verification failure. Please check verification code again.')
            except:
                errormsg = _('Verification failure. Please check verification code again.')
        else:
            errormsg = _('Sorry. Please try again later.')

        return error_page(request, errormsg)
    elif request.method == "GET":
        userform = RegistrationForm()

    return render(
        request,
        "accounts/signup.html",
        {
            'userform': userform,
        }
    )
Exemple #2
0
def edit_article(request, id):
    """Edit article"""
    article = get_object_or_404(Board, pk=id)
    edit_type = 'edit'

    if request.method == "POST":
        editform = BoardEditForm(request.POST, request.FILES, instance=article)
        if editform.is_valid():
            article = editform.save(commit=False)

            image_text = article.get_image_text()
            if image_text in article.content:
                article.has_image = True
            else:
                article.has_image = False
            video_text = article.get_video_text()
            if video_text in article.content:
                article.has_video = True

            if article.status == '2temp':
                article.created_at = timezone.now()
                article.save()
                return redirect(article.get_edit_url())

            article.modified_at = timezone.now()
            article.save()

            request.user.profile.last_article_at = timezone.now()
            request.user.profile.save()

            return redirect(article.get_article_url())
    elif request.method == "GET":
        board_table = BoardTable()
        if article.table >= board_table.get_table_len():
            return error_page(request)

        table_name = board_table.get_table_name(article.table)
        if table_name == '':
            return error_page(request)

        table_desc = board_table.get_table_desc(article.table)
        category_choices = board_table.get_category(article.table)

        editform = BoardEditForm(instance=article)

        if article.status == '2temp':
            edit_type = 'temp'

    return render(
        request, 'boards/edit_article.html', {
            'form': editform,
            'edit_type': edit_type,
            'table_name': table_name,
            'table_desc': table_desc,
            'category_choices': category_choices,
            'category': article.category,
            'created_at': article.created_at,
        })
Exemple #3
0
def new_article(request, table=0):
    """New article"""
    if int(table) == 0 or int(table) == 9 or (int(table) < 8
                                              and not request.user.is_staff):
        return error_page(request)

    if request.method == "POST":
        editform = BoardEditForm(request.POST, request.FILES)
        if editform.is_valid():
            article = editform.save(commit=False)
            if article.status != '1normal' and article.status != '2temp':
                if not request.user.is_staff:
                    errormsg = _("Wrong status from user.")
                    return error_page(request, errormsg)

            image_text = article.get_image_text()
            if image_text in article.content:
                article.has_image = True
            video_text = article.get_video_text()
            if video_text in article.content:
                article.has_video = True

            article.user = request.user
            article.ip = get_ipaddress(request)
            article.table = table
            article.save()

            if article.status == '2temp':
                return redirect(article.get_edit_url())

            request.user.profile.last_article_at = timezone.now()
            request.user.profile.point += settings.POINT_ARTICLE
            request.user.profile.save()

            return redirect(article.get_absolute_url())
    elif request.method == "GET":
        editform = BoardEditForm()

    board_table = BoardTable()
    if int(table) >= board_table.get_table_len():
        return error_page(request)

    table_name = board_table.get_table_name(table)
    if table_name == '':
        return error_page(request)

    table_desc = board_table.get_table_desc(table)
    category_choices = board_table.get_category(table)

    return render(
        request, 'boards/edit_article.html', {
            'form': editform,
            'edit_type': 'new',
            'table_name': table_name,
            'table_desc': table_desc,
            'category_choices': category_choices,
        })
Exemple #4
0
def recruitment(request, table=0, page=0):
    """Recruitment"""
    team_table = TeamTable()
    if int(table) >= team_table.get_table_len():
        return error_page(request)

    table_name = team_table.get_table_name(table)
    if table_name == '':
        return error_page(request)

    if int(page) < 1:
        return redirect('teams:recruitment', table=table, page=1)

    table_desc = team_table.get_table_desc(table)
    list_count = team_table.get_list_count()

    current_page = int(page) - 1
    start_at = current_page * list_count
    end_at = start_at + list_count

    q = Q(status='1normal') | Q(status='7canceled') | Q(status='8full') | Q(status='5hidden')

    total = Team.objects.filter(table=table).filter(q).count()
    lists = Team.objects.filter(table=table).filter(q).order_by('-id')[start_at:end_at]

    index_total = int(ceil(float(total) / list_count))
    index_begin = (current_page / 10) * 10 + 1
    index_end = mindex_end = index_total
    if index_end - index_begin >= 10:
        index_end = index_begin + 9
    mindex_begin = (current_page / 5) * 5 + 1
    if mindex_end - mindex_begin >= 5:
        mindex_end = mindex_begin + 4

    if request.user.is_authenticated():
        writable = True
    else:
        writable = False

    return render(
        request,
        "teams/recruitment.html",
        {
            'lists': lists,
            'total': total,
            'table': table,
            'table_name': table_name,
            'table_desc': table_desc,
            'page': current_page + 1,
            'index_begin': index_begin,
            'index_end': index_end + 1,
            'mindex_begin': mindex_begin,
            'mindex_end': mindex_end + 1,
            'index_total': index_total,
            'writable': writable,
        }
    )
def cancel_sale(request, id=-1):
    id = int(id)
    try:
        sale = Sale.objects.get(id=id, merchant=request.user)
    except:
        return error_page(request, "A sale with the ID %d could not be found." % id)
    if sale.status != Sale.PENDING:
        return error_page(request, "That sale has already been cancelled.")

    sale.cancel()
    return HttpResponseRedirect("/")
Exemple #6
0
def send_email(request):
    """Send email to user for testing purpose"""
    id_email = request.user.email
    signer = TimestampSigner()
    value = signer.sign(id_email)
    subject = u'Test email.'
    body = u'keyCode: %s' % value

    try:
        send_mail(subject, body, settings.EMAIL_HOST_USER, [id_email], fail_silently=False)
        return error_page(request, "Email sent", status=201)
    except SMTPException:
        return error_page(request, "Error!")
Exemple #7
0
def search_reply(request, search_type, search_word, table=0, page=1):
    """Show reply list"""
    board_table = BoardTable()
    if int(table) >= board_table.get_table_len():
        return error_page(request)

    table_name = board_table.get_table_name(table)
    if table_name == '':
        return error_page(request)

    list_count = board_table.get_list_count()

    current_page = int(page) - 1
    start_at = current_page * list_count
    end_at = start_at + list_count

    if search_type == 'writeuser':
        q = Q(status__iexact='1normal') & (
            Q(user__username__iexact=search_word)
            | Q(user__first_name__iexact=search_word))
    else:
        return error_page(request)

    total = Reply.objects.filter(q).count()
    lists = Reply.objects.filter(q).order_by('-id')[start_at:end_at]
    name_list = board_table.get_table_list()

    index_total = int(ceil(float(total) / list_count))
    index_begin = int(current_page / 10) * 10 + 1
    index_end = mindex_end = index_total
    if index_end - index_begin >= 10:
        index_end = index_begin + 9
    mindex_begin = int(current_page / 5) * 5 + 1
    if mindex_end - mindex_begin >= 5:
        mindex_end = mindex_begin + 4

    return render(
        request, "boards/search_reply.html", {
            'lists': lists,
            'total': total,
            'table': table,
            'page': current_page + 1,
            'index_begin': index_begin,
            'index_end': index_end + 1,
            'mindex_begin': mindex_begin,
            'mindex_end': mindex_end + 1,
            'index_total': index_total,
            'name_list': name_list,
            'search_type': search_type,
            'search_word': search_word,
        })
Exemple #8
0
def edit_vault(request, id):
    """Edit vault"""
    if not check_seal(request):
        return redirect('vaults:new_key')

    expired, expiry = key_expired(request)
    if expired:
        return check_key(request)

    vault = get_object_or_404(Vault, pk=id)
    if vault.user != request.user:
        return error_page(request)

    if request.method == "POST":
        editform = VaultEditForm(request.POST, request.FILES, instance=vault)
        if editform.is_valid():
            vault = editform.save(commit=False)
            vault.save()

            return redirect(vault.get_absolute_url())
    elif request.method == "GET":
        editform = VaultEditForm(instance=vault)

    return render(request, "vaults/edit_vault.html", {
        'form': editform,
        'edit_type': 'edit',
        'vault': vault,
        'expiry': expiry,
    })
def accept_offer(request, id=-1):
    try:
        chosen_offer = Offer.objects.get(id=id)
    except:
        return error_page(request, "Offer does not exist.")

    if not chosen_offer.available():
        return error_page(request, "Offer no longer available!")
    else:
        chosen_offer.sale.accept_offer(chosen_offer)
        message = "Congratulations on selling your book! You can contact %s at %s" % (
            chosen_offer.buyer.get_full_name(),
            chosen_offer.buyer.email,
        )

    return index(request, flash=message)
Exemple #10
0
def like_post(request):
    """API like_post"""
    if request.method == 'POST':
        id = request.POST['id']
        ip = get_ipaddress(request)
        user = request.user
        post = get_object_or_404(Blog, pk=id)
        like_users = post.like_users.split(',')

        if post.user == user or ip == post.ip:
            msg = _("You like your own post?")
            return JsonResponse([0, msg], safe=False, status=201)

        if ip not in like_users:
            if post.like_users != '':
                post.like_users += ","
            post.like_users += ip
            post.like_count += 1
            post.save()

            msg = _("You've liked this article")
            return JsonResponse(
                [post.like_count, msg], safe=False, status=201)
        else:
            msg = _("You've already liked")
            return JsonResponse([0, msg], safe=False, status=201)
    else:
        return error_page(request)
Exemple #11
0
def change_status(request, id, status):
    """Change status"""
    article = get_object_or_404(Team, pk=id)

    if request.user == article.user or request.user.is_staff:
        if article.status != status:
            if status == '1normal':
                article.status = status
                article.save()
            elif status == '7canceled' or status == '8full':
                article.status = status
                article.save()

                slot_users = article.slot_users.all()
                for slot_user in slot_users:
                    if slot_user.profile.alarm_full:
                        if slot_user.profile.alarm_list != '':
                            slot_user.profile.alarm_list += ','
                        if status == '8full':
                            alarm_text = 'f:%d' % article.id
                        else:
                            alarm_text = 'c:%d' % article.id
                        slot_user.profile.alarm_list += alarm_text
                        slot_user.profile.alarm = True
                        slot_user.save()
        return redirect(article.get_article_url())
    else:
        return error_page(request)
Exemple #12
0
def toggle_bookmark(request):
    """API toggle_bookmark"""
    if request.method == 'POST':
        app = request.POST['app']
        id = request.POST['id']
        app_id = app + '-' + id
        profile = request.user.profile
        bookmarks = profile.bookmarks.split(',')

        if app_id not in bookmarks:
            if len(bookmarks) > settings.MAX_BOOKMARKS:
                return JsonResponse({'status': 'false'}, status=400)

            if profile.bookmarks != '':
                profile.bookmarks += ","
            profile.bookmarks += app_id
            data = static('icons/stared28.png')
        else:
            regstr = re.escape(app_id) + r"\b(,|)"
            profile.bookmarks = re.sub(regstr, '', profile.bookmarks)
            if profile.bookmarks and profile.bookmarks[-1] == ',':
                profile.bookmarks = profile.bookmarks[:-1]
            data = static('icons/star28.png')

        request.user.profile.save()
        return JsonResponse([data], safe=False, status=201)

    return error_page(request)
Exemple #13
0
def dashboard(request, condition='recent'):
    """Dashboard"""
    post_count = settings.DASHBOARD_POST_COUNT
    comment_count = settings.DASHBOARD_COMMENT_COUNT

    if condition == 'recent':
        order = '-id'
    elif condition == 'view':
        order = '-view_count'
    elif condition == 'like':
        order = '-like_count'
    elif condition == 'comment':
        order = '-comment_count'
    else:
        return error_page(request)

    posts = Blog.objects.filter(status='1normal').order_by(order)[:post_count]
    comments = Comment.objects.filter(
        status='1normal').order_by('-id')[:comment_count]

    total_posts = Blog.objects.filter(status='1normal').count()
    total_comments = Comment.objects.filter(status='1normal').count()
    total_spams = Comment.objects.filter(status='7spam').count()
    total_users = User.objects.count()

    return render(
        request, "blogs/dashboard.html", {
            'posts': posts,
            'comments': comments,
            'condition': condition,
            'total_posts': total_posts,
            'total_comments': total_comments,
            'total_spams': total_spams,
            'total_users': total_users,
        })
Exemple #14
0
def conversation(request, user):
    """Conversation"""
    try:
        other = User.objects.filter(username__iexact=user).get()
    except ObjectDoesNotExist:
        errormsg = _('User does not exist.')
        return error_page(request, errormsg)

    if request.user == other:
        errormsg = _('Cannot send message to yourself.')
        return error_page(request, errormsg)

    if request.method == "POST":
        msgform = MsgForm(request.POST)
        if msgform.is_valid():
            msg = msgform.save(commit=False)
            msg.sender = request.user
            msg.recipient = other
            msg.ip = get_ipaddress(request)
            msg.save()
            other.profile.msg_count += 1
            other.profile.save()

            return redirect('msgs:conversation', user=other)
        else:
            errormsg = _('Form validation Failure')
            return error_page(request, errormsg)
    else:
        q = (Q(sender__username__iexact=other.username) & Q(
            recipient__username__iexact=request.user.username) & (Q(
                recipient_status='1normal') | Q(recipient_status='2read'))) | \
            (Q(sender__username__iexact=request.user.username) & Q(
                recipient__username__iexact=other.username) & Q(
                    sender_status='1normal'))

        msgs = Msg.objects.filter(q).order_by('id')

        unread_msgs = msgs.filter(recipient_status='1normal').filter(
            recipient__username__iexact=request.user.username)
        for um in unread_msgs:
            um.recipient_status = '2read'
            um.save()

        return render(request, "msgs/conversation.html", {
            'msgs': msgs,
            'other': other,
        })
Exemple #15
0
def delete_vault(request, id):
    """Delete vault"""
    vault = get_object_or_404(Vault, pk=id)
    if vault.user != request.user:
        return error_page(request)

    vault.delete()
    return redirect(vault.get_absolute_url())
Exemple #16
0
def kick_player(request):
    """API reload_team"""
    if request.method == 'POST':
        if not request.user.is_authenticated:
            return JsonResponse({'status': 'false'}, status=401)

        id = request.POST['id']
        kick = request.POST['kick_user']
        kick_user = User.objects.filter(username__iexact=kick).get()
        user = request.user
        article = get_object_or_404(Team, pk=id)

        if article.user != user and not user.is_staff:
            return JsonResponse({'status': 'false'}, status=403)

        slots = article.slot_users.all()

        if kick_user in slots:
            article.slot_users.remove(kick_user)
            if article.slot > 1:
                article.slot -= 1

            if article.status == '8full':
                article.status = '1normal'
            article.save()
            slot_users = article.slot_users.all()

            if article.user.profile.alarm_team:
                if article.user.profile.alarm_list != '':
                    article.user.profile.alarm_list += ','
                alarm_text = 'l:%d' % article.id
                article.user.profile.alarm_list += alarm_text
                article.user.profile.alarm = True
                article.user.save()

            if kick_user.profile.alarm_list != '':
                kick_user.profile.alarm_list += ','
            alarm_text = 'k:%d' % article.id
            kick_user.profile.alarm_list += alarm_text
            kick_user.profile.alarm = True
            kick_user.save()

            return render_to_response(
                'teams/show_team.html',
                {
                    'user': user,
                    'table': article.table,
                    'article_id': article.id,
                    'article_user': article.user,
                    'slot_in': article.slot,
                    'empty_slots': article.slot_total - article.slot,
                    'slot_users': slot_users,
                }
            )
        else:
            return JsonResponse({'status': 'false'}, status=404)
    else:
        return error_page(request)
Exemple #17
0
def new_recruitment(request, table=0):
    """New recruitment"""
    if request.method == "POST":
        editform = TeamEditForm(request.POST)
        if editform.is_valid():
            article = editform.save(commit=False)
            if article.status != '1normal':
                if not request.user.is_staff:
                    errormsg = _("Wrong status from user.")
                    return error_page(request, errormsg)
            article.user = request.user
            article.ip = get_ipaddress(request)
            article.table = table
            article.save()

            request.user.profile.last_article_at = timezone.now()
            request.user.profile.point += settings.POINT_ARTICLE
            request.user.profile.save()

            return redirect(article.get_article_url())
    elif request.method == "GET":
        editform = TeamEditForm()

    team_table = TeamTable()
    if int(table) >= team_table.get_table_len():
        return error_page(request)

    table_name = team_table.get_table_name(table)
    if table_name == '':
        return error_page(request)

    table_desc = team_table.get_table_desc(table)
    category_choices = team_table.get_category(table)

    return render(
        request,
        'teams/edit_recruitment.html',
        {
            'form': editform,
            'edit_type': 'new',
            'table_name': table_name,
            'table_desc': table_desc,
            'category_choices': category_choices,
        }
    )
Exemple #18
0
def delete_reply_permanently(request, id):
    """Delete reply permanently"""
    reply = get_object_or_404(Reply, pk=id)
    if reply.status == '6deleted' or reply.status == '5hidden':
        reply.delete()
    else:
        return error_page()

    referer = get_referer(request)
    return redirect(referer)
Exemple #19
0
def delete_article_permanently(request, id):
    """Delete article permanently"""
    article = get_object_or_404(Board, pk=id)
    if article.status == '6deleted' or article.status == '5hidden':
        article.delete()
    else:
        return error_page(request)

    referer = get_referer(request)
    return redirect(referer)
Exemple #20
0
def delete_comment_permanently(request, id):
    """Delete comment permanently"""
    comment = get_object_or_404(Comment, pk=id)
    if comment.status == '6deleted' or comment.status == '7spam':
        comment.delete()
    else:
        return error_page(request)

    referer = get_referer(request)
    return redirect(referer)
Exemple #21
0
def delete_post_permanently(request, id):
    """Delete post permanently"""
    post = get_object_or_404(Blog, pk=id)
    if post.status == '6deleted':
        post.delete()
    else:
        return error_page(request)

    referer = get_referer(request)
    return redirect(referer)
Exemple #22
0
def click(request, alias):
    """Click alias"""
    a = Alias.objects.filter(name__exact=alias)
    if a:
        a[0].clicks += 1
        a[0].save()
        return redirect(a[0].url)
    else:
        errormsg = _('The page you requested is not exist. Please try something else.')
        return error_page(request, errormsg)
Exemple #23
0
def reply_count(request):
    """API reply_count"""
    if request.method == 'POST':
        id = request.POST['id']
        article = get_object_or_404(Board, pk=id)
        count = article.reply_count

        return JsonResponse([count], safe=False, status=201)

    return error_page(request)
Exemple #24
0
def show_post(request, id):
    """Show post"""
    post = get_object_or_404(Blog, pk=id)

    if post.status == '5hidden' and not request.user.is_staff:
        errormsg = _('status_pending')
        return error_page(request, errormsg)
    elif post.status == '6deleted' and not request.user.is_staff:
        errormsg = _('status_deleted')
        return error_page(request, errormsg)
    elif post.status == '2temp' and not request.user == post.user:
        return error_page(request)

    post.view_count += 1
    post.save()

    if post.status != '1normal':
        status_text = post.get_status_text()
    else:
        status_text = ''

    q = Q(status__iexact='1normal') & Q(category__iexact=post.category)

    next_post = Blog.objects.filter(q).order_by('id').filter(id__gt=id)[:3]
    prev_post = Blog.objects.filter(q).order_by('-id').filter(id__lt=id)[:3]
    post_navi = []

    for p in reversed(next_post):
        post_navi.append(p)
    post_navi.append(post)
    for p in prev_post:
        post_navi.append(p)

    return render(
        request,
        "blogs/show_post.html",
        {
            'post': post,
            'status_text': status_text,
            'post_navi': post_navi,
        }
    )
Exemple #25
0
def restore_article(request, id):
    """Restore article"""
    article = get_object_or_404(Board, pk=id)
    if article.status == '6deleted' or article.status == '5hidden':
        article.status = '1normal'
        article.save()
    else:
        return error_page(request)

    referer = get_referer(request)
    return redirect(referer)
Exemple #26
0
def restore_comment(request, id):
    """Restore comment"""
    comment = get_object_or_404(Comment, pk=id)
    if comment.status == '6deleted' or comment.status == '7spam':
        comment.status = '1normal'
        comment.save()
    else:
        return error_page(request)

    referer = get_referer(request)
    return redirect(referer)
Exemple #27
0
def restore_reply(request, id):
    """Restore reply"""
    reply = get_object_or_404(Reply, pk=id)
    if reply.status == '6deleted' or reply.status == '5hidden':
        reply.status = '1normal'
        reply.save()
    else:
        return error_page(request)

    referer = get_referer(request)
    return redirect(referer)
Exemple #28
0
def restore_post(request, id):
    """Restore post"""
    post = get_object_or_404(Blog, pk=id)
    if post.status == '6deleted':
        post.status = '1normal'
        post.save()
    else:
        return error_page(request)

    referer = get_referer(request)
    return redirect(referer)
Exemple #29
0
def edit_recruitment(request, id):
    """Edit recruitment"""
    article = get_object_or_404(Team, pk=id)

    if request.method == "POST":
        editform = TeamEditForm(request.POST, instance=article)
        if editform.is_valid():
            article = editform.save(commit=False)
            article.modified_at = timezone.now()
            article.save()

            request.user.profile.last_article_at = timezone.now()
            request.user.profile.save()

            return redirect(article.get_article_url())
    elif request.method == "GET":
        team_table = TeamTable()
        if article.table >= team_table.get_table_len():
            return error_page(request)

        table_name = team_table.get_table_name(article.table)
        if table_name == '':
            return error_page(request)

        table_desc = team_table.get_table_desc(article.table)
        category_choices = team_table.get_category(article.table)

        editform = TeamEditForm(instance=article)

    return render(
        request,
        'teams/edit_recruitment.html',
        {
            'form': editform,
            'edit_type': 'edit',
            'table_name': table_name,
            'table_desc': table_desc,
            'category_choices': category_choices,
            'category': article.category,
        }
    )
Exemple #30
0
def save_order(request):
    """Save order"""
    if request.method == "POST":
        orders = dict(request.POST.iterlists())['order[]']
        for index, order in enumerate(orders):
            recipe = get_object_or_404(Recipe, pk=order)
            recipe.order = index + 1
            recipe.save()

        return JsonResponse({'status': 'true'}, status=201)

    return error_page(request)
Exemple #31
0
def show_article(request, id, table=-1):
    """Show article"""
    article = get_object_or_404(Board, pk=id)

    if article.status == '5hidden' and not request.user.is_staff:
        errormsg = _('status_hidden')
        return error_page(request, errormsg)
    elif article.status == '6deleted' and not request.user.is_staff:
        errormsg = _('status_deleted')
        return error_page(request, errormsg)
    elif article.status == '2temp' and not request.user == article.user:
        return error_page(request)

    if article.table == 8 and article.status != '3notice' and not (
            request.user.is_staff or request.user == article.user):
        return error_page(request)

    article.view_count += 1
    article.save()

    if int(table) == -1:
        table = article.table
    board_table = BoardTable()
    table_name = board_table.get_table_name(table)
    table_desc = board_table.get_table_desc(table)

    if article.status != '1normal':
        status_text = article.get_status_text()
    else:
        status_text = ''

    return render(
        request, "boards/show_article.html", {
            'article': article,
            'table': table,
            'table_name': table_name,
            'table_desc': table_desc,
            'status_text': status_text,
        })
Exemple #32
0
def delete_reply(request, id):
    """Delete reply"""
    reply = get_object_or_404(Reply, pk=id)
    if request.user == reply.user:
        reply.status = '6deleted'
    elif request.user.is_staff:
        reply.status = '5hidden'
    else:
        return error_page(request)

    reply.save()
    referer = get_referer(request)
    return redirect(referer)
def browse(request, id=-1):

    if id is not -1:  # Browse book interface.
        try:
            sale = Sale.objects.get(id=id, status=Sale.PENDING)
        except:
            return error_page(request, "A sale with the id %d could not be " "found." % int(id))
        viewer = "guest"
        if request.user == sale.merchant:
            viewer = "merchant"
        elif request.user.is_authenticated():
            if len(Offer.objects.filter(sale=sale, status=Sale.PENDING, buyer=request.user)) > 0:
                viewer = "made_offer"
            else:
                viewer = "no_offer"
        offers = Offer.objects.filter(sale=sale, status=Offer.PENDING).order_by("-price", "buyer__first_name")
        return load_page(request, "sale_details.html", {"viewer": viewer, "sale": sale, "offers": offers})
    else:
        if request.user.is_authenticated():
            sales = Sale.objects.exclude(merchant=request.user).filter(status=Sale.PENDING)
        else:
            sales = Sale.objects.filter(status=Sale.PENDING)

        sales = sales.order_by("price", "title", "merchant__last_name")

        error = ""

        title = ""
        isbn = ""
        course = ""

        form = SearchForm(request.GET)
        if form.is_valid():
            title = form.cleaned_data["title"] or ""
            isbn = form.cleaned_data["isbn"] or ""
            course = form.cleaned_data["course"] or ""

            if title != "":
                sales = sales.filter(title__icontains=title)
            if isbn != "":
                sales = sales.filter(isbn__exact=isbn)
            if course != "":
                sales = sales.filter(course__exact=course)

        my_sales = []
        for sale in sales:
            offers = Offer.objects.filter(sale=sale)
            this_sale = {
                "id": sale.id,
                "image": sale.image,
                "title": sale.title,
                "course": sale.course,
                "price": sale.price,
                "merchant": sale.merchant,
                "offers": len(offers.filter(status=Offer.PENDING)),
                "expires": sale.expires,
                "expires_soon": (sale.expires - date.today()) <= timedelta(1),
            }
            my_sales.append(this_sale)
        sales = my_sales

        per_page = 5
        pages = int(ceil(len(sales) / float(per_page)))

        page = int(request.GET.get("page", 1))

        if pages <= 0:
            pages = 1
        if page <= 0:
            page = 1
        if page > pages:
            page = pages

        prev = "?title=%s&isbn=%s&course%s=&page=%s" % (title or "", isbn or "", course or "", (page - 1))
        next = "?title=%s&isbn=%s&course=%s&page=%s" % (title or "", isbn or "", course or "", (page + 1))

        # Calculate the page number. Don't forget any leftovers on the last page.
        # page_number = min(page, ceil(len(sales) / float(per_page)))

        # Calculate the display indices from the page number.
        first = int((page - 1) * per_page)
        last = int(page * per_page)
        sales = sales[first:last]

        return load_page(
            request,
            "browse.html",
            {"sales": sales, "form": form, "error": error, "prev": prev, "next": next, "page": page, "pages": pages},
        )